开发者

DJango - __in database query

I have the following data structure: FruitObject with fields FruitType and FruitColor. On the other hand I have FruitOffer (which is input by user). 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).

So logically I've used __in selection to get needed data:

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 s开发者_开发问答elect and get many-to-many select that fulfills both conditions (for each fruitObject get offerObject that is BOTH of TYPE and COLOR)

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.

How do add AND condition to __in select? 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) )


Use Q objects for lookups https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜