如何检查两个型号的ID嵌套循环?

我的问题是模板的嵌套循环...我用它来检查我的模型sitio.id_sitio是否具有与带有外键的另一模型comprobante.id_sitio等效的ID,然后打印A(如果有)找到结果,如果没有,则为B

条件式工作正常,但我不想多次打印嵌套循环。

如果找到一个结果,我想中断循环并仅打印HTML一次,例如<a href=""> Checkouts </a> 否则,如果结果末尾的记录中不存在,我想打印<p>No payments</p>

我不知道是否必须在views.py中编写查询,还是必须在模板中执行其他操作... 有正确的方法吗?


这是我的代码:

Models.py

class Comprobante(models.Model):
        id_sitio = models.ForeignKey('Sitio',models.DO_NOTHING,db_column='id_sitio',blank=True,null=True)

class Sitio(models.Model):
        id_sitio = models.IntegerField(primary_key=True)
        sitio = models.CharField(max_length=100,null=True)

        def __str__(self):
            return self.sitio

Views.py

def topsitios(request):
    sitio = Sitio.objects.all()[0:100]
    comprobante = Comprobante.objects.all()[0:100]

    context = {'sitio': sitio,'comprobante': comprobante}

    return render(request,"sitio_ptc/topsitios.html",context)

Template.html

{% block content %}

{% for s in sitio %}
<tr>
<th scope="row">  {{ forloop.counter }}</th>
<td> {{ s.sitio }} </td>

<td>
{% for c in comprobante %}
{% if s.id_sitio == c.id_sitio_id %}
<a href="">Checkouts</a>
{% else %}
<p>no payments</p>
{% endif %}
{% endfor %}
</td> 

</tr> 
{% endfor %}
{% endblock %}
waruut 回答:如何检查两个型号的ID嵌套循环?

快速解决方案是:

{% if c.id_sitio_id == s.id_sitio %}

因为Comprobante.id_sitio是与具有自定义主键的模型相关的外键,所以c.id_sitio_id_id是Django添加的后缀,保留主键的值,因此通常在大多数情况下是id字段)存储Sitio.id_sitio的值。

但是我将重构您的代码以使其更清晰,更灵活:

# models.py
class Comprobante(models.Model):
    sitio = models.ForeignKey('Sitio',on_delete=models.SET_NULL,blank=True,null=True)

class Sitio(models.Model):
    name = models.CharField(max_length=100,null=True)

# in the template
...
{% if s.id == c.sitio_id %}
...
,

执行此操作的正确方法是使用Django ORM访问模型的关系。在每个sitio的for循环中,您可以通过comprobante

检查是否存在任何相关的{% if s.comprobante_set.all %}

为了获得更好的性能,您还需要通过comprobante预取相关的Sitio.objects.prefetch_related('comprobante_set').all()记录。这样您就不会遇到N + 1查询问题。

,

您可以在Comprobante类中使用相关的名称属性

class Comprobante(models.Model):
    id_sitio = models.ForeignKey(
        'Sitio',models.DO_NOTHING,related_name='comprobantes',db_column='id_sitio',null=True)

设置了related_name后,您可以在模板中进行检查

{% block content %}
    {% for s in sitio %}
    <tr>
        <th scope="row">  {{ forloop.counter }}</th>
        <td> {{ s.sitio }} </td>
        <td>
        {% if s.comprobantes %}
            {# Hay un comprobante para el sitio #}
            <a href="">Checkouts</a>
        {% else %}
            <p>no payments</p>
        {% endif %}
        </td> 
    </tr> 
    {% endfor %}
{% endblock %}

希望这会有所帮助

本文链接:https://www.f2er.com/3075568.html

大家都在问