djangorestframework: Filtering in a related field

I'll be curious to see a better solution as well. I've used a custom method in my serializer to do that. It's a bit more verbose but at least it's explicit.

Some pseudo code where a GarageSerializer would filter the nested relation of cars:

class MyGarageSerializer(...):
    users = serializers.SerializerMethodField('get_cars')

    def get_cars(self, garage):
        cars_queryset = Car.objects.all().filter(Q(garage=garage) | ...).select_related()
        serializer = CarSerializer(instance=cars_queryset, many=True, context=self.context)

        return serializer.data

Obviously replace the queryset with whatever you want. You don't always need the to give the context (I used it to retrieve some query parameters in the nested serializer) and you probably don't need the .select_related (that was an optimisation).


One way to do this is to create a method on the Model itself and reference it in the serializer:

#Models.py
class MyModel(models.Model):
    #...
    def my_filtered_field (self):
            return self.othermodel_set.filter(field_a = 'value_a').order_by('field_b')[:10]
#Serialziers.py
class MyModelSerialzer(serializers.ModelSerializer):
    my_filtered_field = OtherModelSerializer (many=True, read_only=True)
    class Meta:
        model   = MyModel
        fields  = [
            'my_filtered_field'             ,
            #Other fields ...
        ]