【问题标题】:Django templates _set.all two sub tableDjango 模板 _set.all 两个子表
【发布时间】:2022-01-11 13:18:30
【问题描述】:

我有两张表要检查是否有数据!

型号:

class Children(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    photo = models.ImageField(blank=True, default='avatar.jpg')
 
class Groups(models.Model):
    child = models.ForeignKey(Children, on_delete=models.CASCADE)

模板:

{% if user.children_set.all.groups_set.all.exists %}

就像:

get_groups = Groups.objects.fitler(child__user=request.user).count

但我需要此语句在模板中,因为我正在尝试在用户表上创建 for 循环:

{% for user in users %}
   {{user.username}}
   {% if user.children_set.all.groups_set.all.exists %}
      Yes
   {% else %}
      No
   {% endif %}
{% endfor %}

【问题讨论】:

    标签: django django-models django-templates


    【解决方案1】:

    如果检查数字是这样的最终目标,您也可以在模板中使用 if 条件:

    {% if user.children_set.all.groups_set.count == 0 %}
       <p>this table is empty</p>
    {% else %}
       <p>this table is not empty and go with the looping to print items etc<p> 
    {% endif %}
    

    这可能会有所帮助

    【讨论】:

    • 它不起作用,因为它是一个子子表
    猜你喜欢
    • 2013-02-24
    • 2018-05-04
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    • 2011-01-25
    • 2017-12-29
    • 1970-01-01
    相关资源
    最近更新 更多