Django排除查询集__in为列表中的* every *项

时间:2018-05-22 08:27:26

标签: python django django-models django-queryset

这与Django filter queryset __in for *every* item in listDjango filter queryset __in for *every* item in list (2.0)略有不同 鉴于以下模型:

class Product(BaseModel):
    ''' whatever '''

class Customer(BaseModel):
    blacklist = models.ManyToManyField(Product, blank=True)

class Advisory(BaseModel):
    product_names = models.ManyToManyField(Product)

如果客户维护了一份对其不感兴趣的产品清单。我如何获得给定客户的建议清单?

假设我在我的数据库中有这些:

#   Advisory 1 (should be included as Product 1 isn't in the customers blacklist)
#       product_names
#           Product 1
#           Product 2
#           Product 3
#   Advisory 2 (should be excluded)
#       product_names
#           Product 2
#           Product 3
#   Customer 1
#       blacklist
#           Product 2
#           Product 3
#           Product 4
#           Product 5

如果我使用这样的查询集:

queryset = Advisory.objects.all()
blacklist = Customer.blacklist.all()
queryset = queryset.exclude(product_names__in=blacklist).distinct()

它将排除咨询1和咨询2,因为产品2和3存在于客户黑名单

1 个答案:

答案 0 :(得分:1)

我通过两个步骤找到问题的解决方案:

# Get the queryset with all advisories
queryset = Advisory.objects.all()
# Find the products the customer doesn't care about
blacklist = Customer.objects.get(pk=customer_id).blacklist.all()
# Build a whitelist of products excluding the blacklist from the customer
whitelist = Product.objects.all().exclude(id__in=blacklist)
# And filter the queryset with the new whitelist
queryset = queryset.filter(product_names__in=whitelist).distinct()