基于相关字段过滤Django中的对象,不包括某些值

时间:2016-07-25 09:38:51

标签: django django-models

我有消费者,他们会收到ConsumerEmails。

class Consumer(Model):
    pass

class ConsumerEmail(Model):
    summary = models.TextField()
    consumer = models.ForeignKey(Consumer, related_name="emails")

我想要的是没有收到任何电子邮件或没有电子邮件的消费者列表,除了要求他们验证其电子邮件地址的电子邮件。也就是说,如果我在这个例子中离开了表格,我会想要ID 1,2,3而不是4,5。

╔════╤══════════════════════════════╤════════╗
║ id │ email.summary                │ select ║
╠════╪══════════════════════════════╪════════╣
║ 1  │ NULL                         │ Yes    ║
╟────┼──────────────────────────────┼────────╢
║ 2  │ Sent email verification code │ Yes    ║
╟────┼──────────────────────────────┼────────╢
║ 3  │ Sent email verification code │ Yes    ║
╟────┼──────────────────────────────┼────────╢
║ 3  │ Sent email verification code │        ║
╟────┼──────────────────────────────┼────────╢
║ 4  │ Sent email verification code │ No     ║
╟────┼──────────────────────────────┼────────╢
║ 4  │ Update on your application   │        ║
╟────┼──────────────────────────────┼────────╢
║ 5  │ Update on your application   │ No     ║
╚════╧══════════════════════════════╧════════╝

我的尝试是:

Consumer.objects.exclude(~Q(emails__summary="Sent email verification code"))

但这会生成查询

SELECT   "api_consumer"."id"
FROM     "api_consumer"
WHERE    NOT (
                  NOT (
                           "api_consumer"."id" IN
                           (
                                  SELECT u1."consumer_id" AS col1
                                  FROM   "api_consumeremail" U1
                                  WHERE  u1."summary" = 'sent email verification code')))

这是不对的。什么是正确的ORM查询?

1 个答案:

答案 0 :(得分:0)

consumers_with_emails = ConsumerEmail.objects.exclude(
    summary="Sent email verification code"
).values_list('consumer_id', flat=True).distinct()

Consumer.objects.exclude(
    id__in=consumers_with_emails
)