gpt4 book ai didi

python - Django 排除列表中*每个*项目的查询集 __in

转载 作者:行者123 更新时间:2023-12-01 09:25:19 24 4
gpt4 key购买 nike

这与 Django filter queryset __in for *every* item in list 有点不同和 Django 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 存在于客户黑名单中

最佳答案

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

# 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()

关于python - Django 排除列表中*每个*项目的查询集 __in,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50463123/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com