如何使示例代码更干?

时间:2013-05-28 11:28:35

标签: django

我有以下代码:

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

但是,我想做类似下面的事情,首先我检查对象是否有group如果没有过滤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,
     )

2 个答案:

答案 0 :(得分:4)

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

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

  

QuerySets很懒 - 创建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,
    )

答案 1 :(得分: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,
    )