简体   繁体   中英

Django queryset with Q object

I want to perform a filter operation on my queryset of the form (x=True) or ((x=False) and (some other condition)). When i try the following command, i get an error. Any suggestions.

Operation

Item.objects.filter(mission_id__in=mission_ids).exclude(id__in=attempted_items).filter(
            answers_left_count__gte=1, is_active=True, is_test_data=False
    ).values_list("mission_id", 'mission__items_per_mission', 'mission__send_remaining_items').annotate(
            Count('id')  # Get item count
    ).filter(Q(mission__send_remaining_items=True) | (
    Q(mission__send_remaining_items=False), Q(id__count__gte=F('mission__items_per_mission') + 1))).values_list(
            "mission_id", flat=True)

Error

TypeError: (<Q: (AND: ('mission__send_remaining_items__is', False))>, <Q: (AND: ('id__count__gte', <CombinedExpression: F(mission__items_per_mission) + Value(1)>))>)

I want to perform a filter operation on my queryset of the form (x=True) or ((x=False) and (some other condition))

AND is only , for Q objects when directly passed to filter() , ie

.filter(Q(), Q())

But that's because of how filter() processes its arguments, not the result of combining two Q objects.

ANDing Q objects is done via & :

.filter(Q() & Q())

So your query becomes

.filter(Q() | (Q() & Q()))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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