0

I've an interesting question and want expert views on it.

I've the following models.

class A(models.Model):
    b = ForeignKey(B)
    c = ForeignKey(B)
    d = ForeignKey(B)

class B(models.Model):
    pass

class C(models.Model):
    pass

class D(models.Model):
    pass

Following are my serializers:

class ASearializer(serializers.Serializer):
    b = BSearializer()
    c = CSearializer()
    d = DSearializer()

    class Meta:
        model = A
        fields = ('b', 'c', 'd')

    def create(self, data):
        # I create the instance of A, B, C and D.
        return instance_of_A

class BSearializer(serializers.Serializer):
    class Meta:
        model = B
        fields = '__all__'

class CSearializer(serializers.Serializer):
    class Meta:
        model = C
        fields = '__all__'

class DSearializer(serializers.Serializer):
    class Meta:
        model = D
        fields = '__all__'

My views:-

class View(CreateAPIView):
    serializer_class = Aserializer
    queryset = A.object.all().select_related('b').select_related('c').select_related('d')

Everything works as expected. The request and the response works correctly.

However, the queries fired are not the way it was expected. While returning the data, DRF fires 3 extra queries to filter B, C and D, thereby ignoring the queryset.

1) How to make DRF fire one single JOIN query?

Praful Bagai
  • 16,684
  • 50
  • 136
  • 267
  • The View in your example is a CreateApiView, this mean that no list is returned. I've debugged with django debug toolbar, and I found 4 query for the 4 insertion. If I switch to a ListView, than the select_related do their job, and I found that a single query is fired. – Fran Feb 23 '19 at 11:40
  • ListAPIView does not support POST request – Praful Bagai Feb 23 '19 at 16:26
  • If you want support the creation and the list, you can use `ListCreateAPIView`. Here https://www.django-rest-framework.org/api-guide/generic-views/#generic-views you can find all the existing classes and mixins to support the different request actions. – Fran Feb 24 '19 at 10:50
  • 1
    You didn't understand my question. – Praful Bagai Feb 25 '19 at 05:56
  • I try to reproduce your case but i see only 3 insert into and, before the session update query 3 weird SELECT COUNT(*) AS "__count". – Mau Mar 19 '19 at 15:45

0 Answers0