Django - 在模板循环中获取所有相关内容

Django - Fetch all related in template loop

我有一个数据 table 为每个 Store 对象创建一行。我正在使用 Django 2.1

<tbody>
{% for store in stores %}
    <tr id="table-row">
        <td><a href="/stores/{{ store.pk }}">{{ store.store_number }}</a></td>
        <td><a href="/stores/{{ store.pk }}">{{ store.name }}</a></td>
        <td>{{ store.phone }}</td>
        <td>{{ store.city }}</td>
        <td>{{ store.state }}</td>
        {% for circuit in circuits %}
            <td>{{ circuit }}</td>
        {% endfor %}
        <td>{{ store.postal }}</td>

    </tr>
{% endfor %}
</tbody>

我想要做的是为每个电路创建一个 table 列,其中 store 是给定的商店编号。

型号:

class Store(models.Model):
    store_number = models.IntegerField(default=0000, unique=True)
    name = models.CharField(max_length=100)
    phone = models.CharField(max_length=15)
    xo_tn = models.CharField(max_length=15, null=True)
    street_address = models.CharField(max_length=50, null=True)
    city = models.CharField(max_length=50, null=True)
    state = models.CharField(max_length=50, null=True)
    postal = models.CharField(max_length=15, null=True)
    timezone = models.CharField(max_length=40, null=True)
    date_opened = models.DateField(blank=True, null=True)
    date_closed = models.DateField(blank=True, null=True)

    def __str__(self):
        string = '{0} - {1}'.format(self.store_number, self.name)
        return string

    def number(self):
        return self.store_number

class Circuit(models.Model):
    circuit_id = models.CharField(max_length=100)
    store = models.ForeignKey(Store, null=True, on_delete=models.SET_NULL)
    provider = models.ForeignKey(Provider, blank=True, null=True, on_delete=models.SET_NULL)
    configuration = models.ForeignKey(CircuitConfiguration, null=True, on_delete=models.SET_NULL)
    registered_on = models.DateTimeField(auto_now=True)
    delivered_on = models.DateField(auto_now=True)
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return self.circuit_id

查看:

@login_required
def stores(request):
    stores = Store.objects.exclude(street_address__contains="closed").all()
    context = {
        'stores':stores,  
    }
    return render(request, 'all_stores.html', context)

我还没有尝试过很多东西,因为我不确定如何在不破坏关系或从前端执行查询的情况下做到这一点。

在django 关系中,您可以使用反向访问器。参见 this document

在您的情况下,您的模板代码将是:

<tbody>
{% for store in stores %}
    <tr id="table-row">
        <td><a href="/stores/{{ store.pk }}">{{ store.store_number }}</a></td>
        <td><a href="/stores/{{ store.pk }}">{{ store.name }}</a></td>
        <td>{{ store.phone }}</td>
        <td>{{ store.city }}</td>
        <td>{{ store.state }}</td>
        {% for circuit in store.circuit_set.all %}
            <td>{{ circuit }}</td>
        {% endfor %}
        <td>{{ store.postal }}</td>

    </tr>
{% endfor %}
</tbody>

另见 this question