【问题标题】:F() expression not working with foreign key comparison when None无时 F() 表达式不适用于外键比较
【发布时间】:2019-11-28 15:24:11
【问题描述】:

我正在尝试通过 F() 表达式比较连接中的外键。我构建的 QuerySet 会返回预期的结果,除非 ForeignKey 的值之一是 None。

我正在编写一个简单的 PTO 请求系统。所有 PTORequests 都有一个配置文件(接受请求的人)和一个批准者(在创建时分配,负责批准请求的人)。所有个人资料都有一个他们向其报告的“经理”。我的目标是查询批准者不是配置文件经理的所有 PTORequest。

class PTORequest(models.Model):
    profile = models.ForeignKey(Profile, null=True, on_delete=models.SET_NULL, related_name='pto_requests')
    approver = models.ForeignKey(Profile, null=True, on_delete=models.SET_NULL, related_name='employee_pto_requests')

class Profile(models.Model):
    manager = models.ForeignKey('self', null=True, on_delete=models.SET_NULL, related_name="reports") 

我的查询是:

PTORequest.objects.exclude(approver=F("profile__manager"))

应该足够简单,但结果令人困惑。

>>>pto = PTORequest.create(profile=profile_1, approver=profile_2)
>>>profile_1.manager = profile_3
>>>profile_1.save()
>>>PTORequest.objects.exclude(approver=F("profile__manager")) # returns 'pto', as expected
<QuerySet [<PTORequest: 1>]>
>>>profile_1.manager = None
>>>profile_1.save()
>>>PTORequest.objects.exclude(approver=F("profile__manager")) # returns empty queryset, unexpected
<QuerySet []>

当经理设置为 None 并且 PTORequest 的批准者设置为 profile_3 时,经理 与批准者不同,但不会在查询集中返回。我对 F() 表达式或外键有误解吗?

【问题讨论】:

    标签: django django-models django-queryset


    【解决方案1】:

    发生的情况是 approverNone 并且 profile__manager 也是 None 因为您已经删除了关系。那么排除条件是True,这就是为什么查询集的值是[ ]

    如果您不想排除 None 外键,您可以这样做: .exclude(approver__isnull=False, F("profile__manager"))

    【讨论】:

    • 感谢您的贡献,但在这种情况下批准人不是 None,如下所述:pto = PTORequest.create(profile=profile_1, approver=profile_2)
    猜你喜欢
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    相关资源
    最近更新 更多