简体   繁体   English

在Django中结合〜Q和F?

[英]Combine ~Q and F in Django?

Query 询问

Balance.objects.filter(~Q(fax_date=F('paused_date')))

returns empty qs even though I do have objects that fit the condition "fax date field not equal to paused date". 即使我有符合条件“传真日期字段不等于暂停日期”的对象,也返回空qs。 Is it possible to use ~Q and F together like that? 这样可以同时使用〜Q和F吗?

ran a test like this: 进行了这样的测试:

        deals = Deal.objects.all()
        balance_pre = Balance.objects.filter(~Q(fax_date=F('paused_date')), fax_date__isnull=False, reserved=False)
        agr_nums = list(deals.filter(agr_name__isnull=False).values_list('agr_name', flat=True).distinct())
        agrs_with_fax = 0

        for agr_num in agr_nums:
            try:
                balance_agr = Balance.objects.get(number__icontains=agr_num)
                if balance_agr.fax_date is not None and balance_agr.fax_date != balance_agr.paused_date and not balance_agr.reserved:
                    agrs_with_fax += 1
            except Balance.DoesNotExist:
                pass
        agrs_with_fax2 = 0

        for agr_num in agr_nums:
            try:
                balance_pre.get(number__icontains=agr_num)
                agrs_with_fax2 += 1
            except Balance.DoesNotExist:
                pass

        r = [agrs_with_fax, agrs_with_fax2, balance_agr.fax_date, balance_agr.paused_date, balance_agr.reserved]

r returned is r返回的是

[55, 0, datetime.date(2018, 7, 11), None, False]

I don't see my error, both cycles should return same result. 我没有看到我的错误,两个周期应该返回相同的结果。

I created a Balance model in a fresh project just to test that print(qs.query) will show you the generated query(not in all cases) in this case. 我在一个新项目中创建了一个Balance模型,只是为了测试print(qs.query)在这种情况下将向您显示生成的查询(并非在所有情况下)。 I used also exclude as @daniel-roseman suggested to prove that they were equivalent. 我还使用了exclude因为@ daniel-roseman建议证明它们是等效的。 I hope this help you. 希望对您有所帮助。

>>> from django.db.models import F, Q
>>> qs = Balance.objects.filter(~Q(fax_date=F('paused_date')))
>>> print(qs.query)
SELECT "so_balance"."id", "so_balance"."fax_date", "so_balance"."paused_date" 
FROM "so_balance" WHERE NOT ("so_balance"."fax_date" = 
("so_balance"."paused_date"))
>>> qs = Balance.objects.exclude(fax_date=F('paused_date'))
>>> print(qs.query)
SELECT "so_balance"."id", "so_balance"."fax_date", "so_balance"."paused_date" 
FROM "so_balance" WHERE NOT ("so_balance"."fax_date" = 
("so_balance"."paused_date"))

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

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