【发布时间】:2019-10-04 11:13:14
【问题描述】:
我的 Django 应用程序有两个模型“项目”和“颜色”,分别代表数据库表“项目”和“颜色”。 Django 模板“mytemplate.html”使用“for”循环呈现从数据库收集的数据,打印出带有属性的项目列表。
“items”表的字段之一是一个数字 id,对应于“colors”表中的文本字段。 目前,我可以显示所有项目及其名称和颜色数字 id 'cid'(参见下面的代码)。
但我需要在模板循环中打印项目的颜色名称而不是它的“cid”/“id”。实现这一目标的最有效方法是什么?我是否需要一个中间数据结构,改变我的数据库来定义一个外键 (items(cid) --> colors(id)),...?
我不确定是否要使用外键 (items(cid) --> colors(id)),因为在第一次插入项目时,“cid”可能是未定义的 (NULL)。
表格“项目”
+------+------+------+
| id | cid | name |
+------+------+------+
| 1 | 3 | barZ |
| 2 | 3 | barC |
| 3 | 1 | barE |
| 3 | 2 | barD |
| 4 | 1 | barA |
+------+------+------+
表格“颜色”
+------+---------+
| id | name |
+------+---------+
| 1 | red |
| 2 | white |
| 3 | blue |
+------+---------+
models.py
from django.db import models
class Items(models.Model):
cid = models.IntegerField(blank=True, null=True)
name = models.TextField(blank=True, null=True)
class Meta:
managed = False
db_table = 'items'
class Colors(models.Model):
name = models.TextField(blank=False, null=False)
class Meta:
managed = False
db_table = 'colors'
views.py
from django.shortcuts import render
from .models import Items
from .models import Colors
def item_list(request):
items = Items.objects.all().order_by('id')
colors = Colors.objects.all().order_by('name')
return render(request,'mytemplate.html',{
'items': items,
'colors': colors
})
mytemplate.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Foos</title>
</head>
<body>
{% block page_content %}
<table>
{% for item in items %}
<tr>
<td>{{ items.name }}</td>
<td>{{ items.cid }}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
</body>
</html>
【问题讨论】:
-
在问题中包含您的
models -
@ans2human:说得好,完成了。关于实际问题的任何提示?
标签: python django python-3.x database