3

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?

coffee-grinder
  • 26,940
  • 19
  • 56
  • 82
ilse2005
  • 11,189
  • 5
  • 51
  • 75
  • Why are you calling `.all()` after `.select_related()`? I think that may be related to the issue here. – Kevin Brown-Silva Jul 31 '15 at 19:31
  • @KevinBrown I tried that already. It does not help. I think the problem is somehow related to the model inheritance and that related queries are not saved when downcasting models – ilse2005 Aug 01 '15 at 09:53
  • What does Django Debug Toolbar say that the source of the query is? – Kevin Brown-Silva Aug 01 '15 at 13:24
  • Here is the toolbar output: /home/ilse/python_wgcast/lib/python3.4/site-packages/rest_framework/serializers.py in to_representation(430) attribute = field.get_attribute(instance) /home/ilse/python_wgcast/lib/python3.4/site-packages/rest_framework/fields.py in get_attribute(300) return get_attribute(instance, self.source_attrs) /home/ilse/python_wgcast/lib/python3.4/site-packages/rest_framework/fields.py in get_attribute(71) instance = getattr(instance, attr) – ilse2005 Aug 01 '15 at 13:47
  • Try swapping your call out with `prefetch_related` to see if it is the one you need to use. – Kevin Brown-Silva Aug 01 '15 at 13:50
  • @KevinBrown that's not working either :( – ilse2005 Aug 02 '15 at 13:20

0 Answers0