How to combine django “prefetch_related” and “valu

2020-04-06 03:09发布

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'

标签: python django
1条回答
成全新的幸福
2楼-- · 2020-04-06 03:35

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

查看更多
登录 后发表回答