Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select_related queryset with ModelSerializer in Django rest framework

I'm trying to use the "select_related" queryset method with DRF serializers, but this example is still doing a lot of sql queries.

How can I get the related object "model_b" from select_related method?

class Model_A(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    model_b = models.ForeignKey(Model_B, null=True, blank=True)

class Model_B(models.Model):
    title = models.CharField(max_length=100)


class Model_A_Serializer(serializers.ModelSerializer):
    model_b = Model_B_Serializer(source="model_b")
    class Meta:
        model = Model_A
        fields = ('title', 'model_b')

class Model_B_Serializer(serializers.ModelSerializer):
    class Meta:
        model = Model_B


class Model_A_View(viewsets.ModelViewSet):
    serializer_class = Model_A_Serializer
    queryset = Model_A.objects.select_related('model_b').all()
like image 697
Dilvane Zanardine Avatar asked Jun 22 '15 17:06

Dilvane Zanardine


People also ask

What is QuerySet in Django REST Framework?

The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects. The default behavior of REST framework's generic list views is to return the entire queryset for a model manager.

How do I change the foreign key value in Django REST Framework?

As stated in the documentation, you will need to write your own create() and update() methods in your serializer to support writable nested data. You will also need to explicitly add the status field instead of using the depth argument otherwise I believe it won't be automatically added to validated_data .

What is the use of Select_related () in Django ORM query?

Using select_related() 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.

What is Select_related and Prefetch_related in Django?

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.


1 Answers

Use prefetch_related instead.

queryset = Model_A.objects.all().prefetch_related('model_b')

Also, you can log your sql queries to the console with this answer

like image 81
Ross Rogers Avatar answered Sep 30 '22 02:09

Ross Rogers