我有MySQL DB:
在Django模型中:
class Record(models.Model):
schema_id = models.IntegerField()
project_id = models.IntegerField()
name = models.CharField(max_length=50)
class Value(models.Model):
record = models.ForeignKey(Record)
key = models.ForeignKey(Key)
value = models.CharField(max_length=255)
class Key(models.Model):
name = models.CharField(max_length=50)
encode = models.BooleanField(default=False, blank=True)
在输出时,它应如下所示:
## record.name ##
key.name - value.value
key.name - value.value
...
## record.name ##
key.name - value.value
key.name - value.value
...
我尝试使用以下代码执行此操作,但它对数据库进行了太多查询。
#in view
records = Record.objects.filter(project_id=1)
#in template
{% for record in records %}
<table>
<tr>
<td class="legend">Record:</td>
<td>{{ record.name }}</td>
</tr>
{% for value in record.value_set.all %}
<tr>
<td class="legend">{{ value.key.name }}:</td>
<td>{{ value.value }}</td>
</tr>
{% endfor %}
</table>
{% endfor %}
使用.select_related()我可以获得2个查询中的所有数据,但是如何在模板中迭代这些数据以获得类似的结构?
records = Record.objects.filter(project_id=1)
values = Value.objects.filter(record__in=records).select_related().order_by('record')