我有一个数据表,该数据表为每个 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>
我要为每个电路创建一个表列,其中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)
我还没有尝试过很多东西,因为我不确定如何才能做到这一点而又不会破坏关系或从前端执行查询。
答案 0 :(得分:1)
在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。