2

我从查询集中获取相关对象,但它有进一步的相关查询,如何获取这些对象?

class PropertyTaxItem(models.Model):
    property = models.ForeignKey(Property)

class Property(models.Model):
    citizens = models.ManyToManyField(Citizen, null=True, through = 'Ownership',help_text="a property could belong to multiple citizens")

class Citizen(models.Model):
   first_name = models.CharField(max_length = 50, help_text = 'First name')
   last_name = models.CharField(max_length = 50, help_text = 'Last name')

我得到了市民部分:

items = PropertyTaxItem.objects.filter(i_status='active').select_related('property_id').prefetch_related('property_id.citizens')
for i in items:
    pp.pprint(i.citizens.__dict__)

输出是:

{'_db': None,
'_fk_val': 10092,
'_inherited': False,
'core_filters': {'property__pk': 10092},
'creation_counter': 69,
'instance': <Property: 306 GASHIHA, KAGINA, Kicukiro,Kicukiro>,
'model': <class 'citizen.models.Citizen'>,
'prefetch_cache_name': 'citizens',
'query_field_name': 'property',
'reverse': False,
'source_field_name': 'asset_property',
'symmetrical': False,
'target_field_name': 'owner_citizen',
'through': <class 'property.models.Ownership'>}

但我想得到公民的物品,例如:

{'id': 18980,
 'first_name': 'Jack',
 'last_name' : 'blablabla',
 ....
 }

怎么做?

4

1 回答 1

2

你有几个问题。您正在查询PropertyTaxItem的哪些外键Property,然后有多个Citizens。这将是选择相关“property s and prefetch theproperty.citizens ”的正确查询

items = PropertyTaxItem.objects.filter(i_status='active').select_related('property').prefetch_related('property__citizens')

您可以像这样访问公民:

for i in items:
    citizens = i.property.citizens.all() # now you have a queryset of citizens. 
    # To get a list of dictionaries, you can call `.values()` on the queryset.
    pp.pprint(citizens.values())

您将遇到的另一个可能的问题是citizens使用自定义直通模型。ManyToManyField使用自定义尽管模型时,查询集有一些限制。

于 2013-11-04T01:10:36.963 回答