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()
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.
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 .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With