在Django中结合〜Q和F?

时间:2018-09-17 13:49:07

标签: python django functools

查询

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

即使我有符合条件“传真日期字段不等于暂停日期”的对象,也返回空qs。这样可以同时使用〜Q和F吗?

进行了这样的测试:

        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返回的是

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

我没有看到我的错误,两个周期应该返回相同的结果。

1 个答案:

答案 0 :(得分:1)

我在一个新项目中创建了一个Balance模型,目的是测试print(qs.query)在这种情况下将向您显示生成的查询(并非在所有情况下)。我还使用了exclude,因为@ daniel-roseman建议证明它们是等效的。希望对您有帮助。

>>> 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"))