Django REST Framework nested serializer and select_related

2k Views Asked by At

I have the following setup: I am using django-rest-framework and django-model-utils InheritanceManager to automatically get the child objects.

models.py:
class Location(models.Model):
    address = models.CharField(max_length=255)

class OfferParent(models.Model):
    location = models.OneToOneField(Location)
    ...
    objects = InheritanceManager()

class OfferChild(OfferParent):
    ...


serializers.py:
class LocationSerializer(ModelSerializer):
    class Meta:
        model = Location

class OfferSerializer(ModelSerializer):
    location  = LocationSerializer()
    class Meta:
        model = Offer


view.py:
class OfferViewSet(ModelViewSet):
    ...
    def get_queryset(self):
        return Offer.objects.select_related('location').all().select_subclasses()

My problem is that the select_related isn't working properly. When I call the retrieve action I see two queries in the debug toolbar instead of one. The first one is the expected inner join with the location table. But then there is an additional query to the location table:

SELECT ••• FROM "offers_offerlocation" WHERE "offers_offerlocation"."id" = 92 

So I am using select_related to join the tables but somehow the serializer makes an additional query to the database.

If I don't use the rest-framework and get an object directly,

Offer.objects.select_related('location').select_subclasses().first()

it works as excepted and it hits the database only once.

Does anyone know how to solve this?

0

There are 0 best solutions below