简体   繁体   中英

How to combine django "prefetch_related" and "values" methods?

How can prefetch_related and values method be applied in combination?

Previously, I had the following code. Limiting fields in this query is required for performance optimization.

Organizations.objects.values('id','name').order_by('name')

Now, I need to prefetch its association and append it in the serializer using "prefetch_related" method.

Organizations.objects.prefetch_related('locations').order_by('name')

Here, I cannot seem to find a way to limit the fields after using "prefetch_related".

I have tried the following, but on doing so serializer does not see the associated "locations".

Organizations.objects.prefetch_related('locations').values("id", "name").order_by('name')

Model Skeleton:

class Organizations(models.Model):
    name = models.CharField(max_length=40)

class Location(models.Model):
    name = models.CharField(max_length=50)
    organization = models.ForeignKey(Organizations, to_field="name", db_column="organization_name", related_name='locations')

    class Meta:
        db_table = u'locations'

Use only() to limit number of fields retrieved if you're concerned about your app performances. See reference .

In the example above, this would be:

Organizations.objects.prefetch_related('locations').only('id', 'name').order_by('name')

which would result in two queries:

SELECT id, name FROM organizations;
SELECT * from locations WHERE organization_name = <whatever is seen before>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM