djangorestframework:在相关字段中进行过滤 [英] djangorestframework: Filtering in a related field

查看:410
本文介绍了djangorestframework:在相关字段中进行过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我想从ModelSerializer的相关字段中过滤掉非活动用户。我尝试动态限制相关字段的查询以及以下内容: p>

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',)

这两种方法都不适用于过滤查询。我想这样做一个嵌套的相关的Serializer类作为一个字段(但是甚至不能使它与一个RelatedField一起使用)。

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

如何过滤queryset for嵌套关系?

How do I filter queryset for nested relation?

推荐答案

我会很好奇看到一个更好的解决方案。我在序列化器中使用了一个自定义方法。这有点更冗长,但至少它是明确的。

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.

一些伪代码,其中GarageSerializer将过滤汽车的嵌套关系:

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

显然用任何你想要的替换查询集。你不总是需要给上下文(我用它来在嵌套的序列化程序中检索一些查询参数),你可能不需要.select_related(这是一个优化)。

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

这篇关于djangorestframework:在相关字段中进行过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆