djangorestframework: Filtering in a related field

2019-02-07 23:29发布

问题:

Basically, I want to filter out inactive users from a related field of a ModelSerializer. I tried Dynamically limiting queryset of related field as well as the following:

class MySerializer(serializers.ModelSerializer):
  users = serializers.PrimaryKeyRelatedField(queryset=User.objects.filter(active=True), many=True)
  class Meta:
    model = MyModel
    fields = ('users',)

Neither of these approaches worked for just filtering the queryset. I want to do this for a nested related Serializer class as a field (but couldn't even get it to work with a RelatedField).

How do I filter queryset for nested relation?

回答1:

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).