My Django application has two Models 'Items' & 'Colors' representing database tables 'items' and 'colors'. A Django template 'mytemplate.html' renders data gathered from the database with a 'for' loop, printing out a list of items with their properties.
One of the fields of 'items' table is a numeric id that correspond to a text field in 'colors' table. Currently I can display all the items with their names and their color numeric id 'cid' (see code below).
But I need to print the color name of an item instead of its 'cid'/'id' within the template loop. What is the most efficient way to achieve this? Do I need an intermediary data structure, alter my database to define a foreign key (items(cid) --> colors(id)), ... ?
I'm not sure that I want to use a foreign key (items(cid) --> colors(id)) because at the time of first insertion of items 'cid' could be undefined (NULL).
Table 'items'
+------+------+------+
| id | cid | name |
+------+------+------+
| 1 | 3 | barZ |
| 2 | 3 | barC |
| 3 | 1 | barE |
| 3 | 2 | barD |
| 4 | 1 | barA |
+------+------+------+
Table 'colors'
+------+---------+
| 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>
modelsin the question