我从queryset中获取了相对对象,但它有另一个相对查询,如何获取这些对象?
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')
我得到了citzien部分:
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',
....
}
怎么做?
答案 0 :(得分:2)
你有一些问题。您正在查询PropertyTaxItem
Property
的哪些外键,然后有多个Citizen
s。这将是一个正确的查询,以选择相关的'属性s and prefetch the
property.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
查询集存在一些限制。