简体   繁体   English

如何通过排除两个参数来过滤 Django 中的查询集

[英]How to filter a queryset in django by excluding with two parameters

I have a view in django that looks as follows:我在 Django 中有一个如下所示的视图:

class ExploreListingView(generics.ListAPIView):
    serializer_class = ListingSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        return Listing.objects.exclude(user=self.request.user, claimed=True)

The result I expect is to filter out any listings that are assigned with the current user and are claimed, however the filter doesn't work, but when I remove either parameter it works just fine.我期望的结果是过滤掉分配给当前用户并声明的所有列表,但是过滤器不起作用,但是当我删除任一参数时,它工作得很好。 How do I exclude it so I can use more than one parameter.我如何排除它以便我可以使用多个参数。

事实证明,我所要做的就是链接排除方法Listing.objects.exclude(user=self.request.user).exclude(claimed=True)

Listing.objects.filter(user=self.request.user, claimed=True)

You select entries that field user is equal self.request.user and claimed is True您选择字段 user 等于 self.request.user 并声称为 True 的条目

and you can use :你可以使用:

Listing.objects.filter(user=self.request.user).exclude(claimed=True)

both ways is worked but the first is clearly code.两种方式都有效,但第一种显然是代码。

By "AND(&)" operator:通过“AND(&)”运算符:

from django.db.models import Q
    Listing.objects.filter(Q(user=self.request.user) & Q(claimed=True))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM