2013-11-04 81 views
2

我從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

是完整的輸出,還是有更多? – aIKid

+0

這不是完整的列表輸出,因爲我想要獲取citizen.id或citizen.first_name – user504909

回答

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查詢集有一些限制。