Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

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'
like image 479
Sudhir Shrestha Avatar asked Mar 27 '17 19:03

Sudhir Shrestha


People also ask

What is the difference between Select_related and Prefetch_related?

select_related() “follows” foreign-key relationships, selecting additional related-object data when it executes its query. prefetch_related() does a separate lookup for each relationship and does the “joining” in Python.

What is Select_related in Django?

Django offers a QuerySet method called select_related() that allows you to retrieve related objects for one-to-many relationships. This translates to a single, more complex QuerySet, but you avoid additional queries when accessing the related objects. The select_related method is for ForeignKey and OneToOne fields.

What does .values do in Django?

values() Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable. Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.

How do I get QuerySet in Django?

You get a QuerySet by using your model's Manager . Each model has at least one Manager , and it's called objects by default. Access it directly via the model class, like so: >>> Blog.objects <django.db.models.manager.Manager object at ...> >>> b = Blog(name='Foo', tagline='Bar') >>> b.objects Traceback: ...


1 Answers

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

like image 62
Antwan Avatar answered Sep 18 '22 22:09

Antwan