如何检查django中多个对象的queryset是否为空?

时间:2018-01-29 22:15:16

标签: django django-templates

因此,我的模板正在接收一个与其他3个模型具有通用外键关系的对象,现在我需要检查是否存在所有这三个模型,以便根据存在和不存在的内容向用户显示自定义消息存在。

以下是一些观点: Person Object附有3个不同的模型:

  1. 地址
  2. 电子邮件
  3. 电话
  4. 如果所有3都不存在,那么我想让模板说出来 `没有找到联系方式,您可以添加新的联系信息“

    但是,即使三者中的任何一个存在,也不要显示消息。我试过这个:

    {% if person.address.all and person.email.all and person.phone.all %}
        <!-- Do something here to show the details of each object -->
    
    {% else %}
        <!-- Show the default message -->
    
    {% endif %}
    

    但这里发生的是,如果地址存在,但电话和电子邮件不存在,它将显示消息 - 这不是我想要的。我如何实现我想要的结果?我可以检查Null吗?

2 个答案:

答案 0 :(得分:1)

我建议创建一个属性并在模板中使用它,以避免在模板中放置如此​​多的逻辑:

在模型中:

class Person(models.Model):
    # ...
    @property
    def has_contact_details(self):
        return self.address.exists() or self.email.exists() or person.phone.exists()

在模板中:

{% if person.has_contact_details %}
    <!-- Do something here to show the details of each object -->

{% else %}
    <!-- Show the default message -->

{% endif %}

答案 1 :(得分:0)

使用'或'代替'和'。如果您使用'和',只有当每个电子邮件和电话和地址都至少有一条记录时,它才会返回true。

请参阅链接以便更好地理解'和'和'或'。 The Peculiar Nature of and and or

{% if person.address.all or person.email.all or person.phone.all %}
    <!-- Do something here to show the details of each object -->

{% else %}
    <!-- Show the default message -->

{% endif %}