'Avoid multiples queries on serializer with `PrimaryKeyRelatedField` in a `ListField`

I have the following serializer

class SomeSerializer(serializers.Serializer):
    fields = serializers.ListField(
        allow_empty=False,
        child=serializers.PrimaryKeyRelatedField(queryset=someModel.objects.all())
    )

When I run the following code on my view/code:

serializer = SomeSerializer(data={'fields': [1, 2, 3, 4]})
serializer.is_valid()

4 different queries are run against the DB, one get(id) for each someModel. Is there any way to ask the serializer to perform just one query?, that way the serializer uses something like:

queryset.filter(pk__in=[1, 2, 3, 4])

instead of:

queryset.get(1)
queryset.get(2)
queryset.get(3)
queryset.get(4)

I tried digging on the django-rest-framework source code and it looks like it only performs get in order to get the data of each model. But maybe I'm missing something.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source