select_related queryset with ModelSerializer in Django rest framework

18.6k views Asked by At

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()
1

There are 1 answers

3
Ross Rogers On

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