如何使用其他模型值过滤结果 - django restframework

时间:2016-08-23 09:00:47

标签: django django-rest-framework

我有4张桌子:

Book:
 - id
 - name
 - user_id #(ForeignKey)
 - visitor_id #(ForeignKey)

Car:
 - id
 - name
 - user_id #(ForeignKey)
 - visitor_id #(ForeignKey)

Pen:
 - id
 - name
 - user_id #(ForeignKey)
 - visitor_id #(ForeignKey)

Role:
 - id
 - obj_type #(ChoicesField. equals `1`,`2` or `3`)
 - obj_id
 - obj_role #(Boolean)
 - visitor_id #(ForeignKey)

现在我在序列化器中有这个:

class BookSerializer(serializers.ModelSerializer):
    queryset = Book.objects.filter(?!?!?) # Here I need help
    serializer_class = BookSerializer

我想根据Role结果检查Book表并过滤Role。我怎么能这样做?什么是最好的解决方案?

我想要这样的事情:

queryset = Book.objects.filter(
    ID__in(Role.objects.filter(user=request.user, obj_id=book_id, role__gt=0))
)

1 个答案:

答案 0 :(得分:1)

您可以定义get_queryset方法:

class BookSerializer(serializers.ModelSerializer):
    queryset = Book.objects.all()

    def get_queryset(self):
        # current user is self.request.user
        return self.queryset.filter(....)

例如,如果您只想让图书的所有者查看/编辑该图书:

class BookSerializer(serializers.ModelSerializer):
    queryset = Book.objects.all()
    # ...

    def get_queryset(self):
        return self.queryset.filter(user_id=self.request.user.pk)

更新:你需要这样的东西:

items = Role.objects.filter(user=request.user, role__gt=0).values_list("pk", flat=True)
return self.queryset.filter(pk__in=items)