How to get a django template to pull information from two different models?(如何获取 django 模板以从两个不同的模型中提取信息?)
问题描述
I am coding a basic django application that will show a table of current store sales, based off of information from a MariaDB database.
The data is entered into the database through a seperate process, so it isn't created in Django, it is just using a simple python script to load a csv file and parse it into an Insert query. There are two models in my code, Stores and ShowroomData. Showroomdata holds all of the records from the python script, however it does not hold any store information. I would like for it to be able to show all of the showroom data as well as the store's location title which is not stored in the ShowroomData model. I know I need to seperate models but can not figure out how to get them to link together.
class ShowroomData(models.Model):
storeid = models.IntegerField(default=0) # Field name made lowercase.
date = models.DateField() # Field name made lowercase.
time = models.TimeField() # Field name made lowercase.
sales = models.DecimalField(max_digits=10, decimal_places=2) # Field name made lowercase.
tax = models.DecimalField(max_digits=10, decimal_places=2) # Field name made lowercase.
class Meta:
unique_together = (('storeid', 'date', 'time'),)
db_table = 'showroomdata'
class Stores(models.Model):
storeid = models.IntegerField(primary_key=True)
location = models.CharField()
I would like for it to be able to output a table like so:
StoreID - Location - Date - Time - Sales - Tax
Here is my WIP html file.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Trickle</title>
</head>
<body>
<h1>Current Showroom Data</h1>
{% if current_showroom %}
<table>
<thead>
<th>Store Number</th>
<th>Location</th>
<th>Date</th>
<th>Sales</th>
<th>Tax</th>
</thead>
{% for store in current_showroom %}
<tr>
<td>{{ store.storeid }}</td>
</tr>
{% endfor %}
</table>
{% endif %}
</body>
</html>
The storeid
field on the ShowroomData model of actually a foreign key. So you should declare it as such:
class ShowroomData(models.Model):
store = models.ForeignKey("Stores", db_column="storeid")
Now you can follow that fk in your template. Assuming current_showroom
is a queryset of ShowroomData instances:
{% for store in current_showroom %}
<tr>
<td>{{ store.storeid }}</td>
<td>{{ store.store.name }}</td>
</tr>
{% endfor %}
这篇关于如何获取 django 模板以从两个不同的模型中提取信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何获取 django 模板以从两个不同的模型中提取信息?


基础教程推荐
- 从字符串 TSQL 中获取数字 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01