How to apply the prefetch_related and values method in combination?
I used to have the following code. The field constraint in this query is required to optimize performance.
Organizations.objects.values('id','name').order_by('name')
Now I need to pre-select its union and add it to the serializer using the prefetch_related method.
Organizations.objects.prefetch_related('locations').order_by('name')
Here I cannot find a way to limit the fields after using "prefetch_related".
I tried the following, but the serializer does not see the associated "locations".
Organizations.objects.prefetch_related('locations').values("id", "name").order_by('name')
Skeleton Models:
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'
source
share