0

我有以下代码:

  for e in Contact.objects.filter(contact_owner=batch.user, group=batch.group):
            msg = Message.objects.create(
                recipient_number=e.mobile,
            )

但是,我想做类似下面的事情,首先我检查对象是否有一个groupif not 过滤器,contact而不是其他过滤器组。

如您所见,这不是很干燥。怎样才能做得更好?

 if self.group == None:
        for e in Contact.objects.filter(contact_owner=batch.user, contact=batch.group):
        msg = Message.objects.create(
            recipient_number=e.mobile,
        )

 else:
     for e in Contact.objects.filter(contact_owner=batch.user, group=batch.group):
     msg = Message.objects.create(
        recipient_number=e.mobile,
     )
4

2 回答 2

4

您应该在您的案例中考虑的想法来自

https://docs.djangoproject.com/en/dev/topics/db/queries/#chaining-filters

QuerySet 是惰性的——创建 QuerySet 的行为不涉及任何数据库活动。您可以整天将过滤器堆叠在一起,在评估 QuerySet 之前,Django 不会实际运行查询

这允许您逐块构建查询。

 q = Contact.objects.filter(contact_owner=batch.user)
 if self.group == None:
      q = q.filter(contact=batch.group)
 else
      q = q.filter(group=batch.group)

 for e in q:
    msg = Message.objects.create(
        recipient_number=e.mobile,
    )
于 2013-05-28T11:35:27.890 回答
1

如果您更喜欢这种较短的书写方式,您也可以使用 if 运算符

q=Contact.objects.filter(contact_owner=batch.user)
q = q.filter(contact=batch.group) if self.group is None else q.filter(group=batch.group)
for e in q:
    msg = Message.objects.create(
        recipient_number=e.mobile,
    )
于 2013-05-28T11:40:09.647 回答