简体   繁体   English

DJango - __in 数据库查询

[英]DJango - __in database query

I have the following data structure: FruitObject with fields FruitType and FruitColor .我有以下数据结构: FruitObject字段FruitTypeFruitColor On the other hand I have FruitOffer (which is input by user).另一方面,我有FruitOffer (由用户输入)。 It has same fields as FruitObject and is being input by user (some kind of demand-support pairing system; we input FruitObjects and user input FruitOffers; the task is to pair them and see what a user has to offer us - to select only those FruitObjects that are equal to FruitOffers for specific user).它与FruitObject具有相同的字段并且由用户输入(某种需求支持配对系统;我们输入 FruitObjects 和用户输入 FruitOffers;任务是将它们配对并查看用户必须为我们提供什么 - select 只有那些FruitObjects 等于特定用户的 FruitOffers)。

So logically I've used __in selection to get needed data:所以从逻辑上讲,我使用__in selection 来获取所需的数据:

select = FruitObject.objects.filter(FruitType__in=FruitOffer.objects.filter(user=request.user).values("FruitType"))

Now comes the hard part for me - I need to add FruitColor to the select and get many-to-many select that fulfills both conditions (for each fruitObject get offerObject that is BOTH of TYPE and COLOR)现在对我来说是困难的部分 - 我需要将 FruitColor 添加到 select 并获得满足这两个条件的多对多 select (对于每个fruitObject获取同时是类型和颜色的offerObject)

select = FruitObject.objects.filter(FruitType__in=FruitOffer.objects.filter(user=request.user).values("FruitType"), FruitColor__in=FruitOffer.objects.filter(user=request.user).values("FruitColor"))

But comma is operating more like OR in this case and returns me all values that are of specific Type or of specific Color.但在这种情况下,逗号的操作更像 OR,它会返回所有特定类型或特定颜色的值。

How do add AND condition to __in select?如何在 select 中添加AND条件? If i'd like to add more conditions (like price or taste), will it be done in same way?如果我想添加更多条件(如价格或口味),会以同样的方式完成吗? Thanks in advance.提前致谢。

The hard way.艰难的路。

FruitObject.objects.filter(reduce(operator.or_, (Q(FruitColor=color, FruitType=type) for (color, type) in FruitOffer.objects.filter(user=request.user).values_list('FruitColor', 'FruitType'))))
from django.db.models import Q
fruit_type = FruitOffer.objects.filter(user=request.user).values("FruitType")
fruit_color= FruitOffer.objects.filter(user=request.user).values("FruitColor")

select = FruitObject.objects.filter( Q(FruitType__in=fruit_type)) & Q(FruitColor__in=fruit_color) )

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

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