user504909
user504909

Reputation: 9549

I get the the queryset, how to get the relative objects?

I get the relative objects from queryset, but it have a further relative query, how to get those objects?

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')

my getting the citzien part:

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__)

the output is:

{'_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'>}

but I want get the items of citizens like:

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

how to do it?

Upvotes: 2

Views: 304

Answers (1)

jproffitt
jproffitt

Reputation: 6355

You have a few issues. You are querying PropertyTaxItem which foreign keys to Property, which then has multiple Citizens. This would be a correct query to select the related 'propertys and prefetch theproperty.citizens`

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

You can access the citizens like this:

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())

Another possible problem you will have is that citizens uses a custom through model. There are some limitations on ManyToManyField query sets when using custom though models.

Upvotes: 2

Related Questions