如何获得Django模板以从两个不同的模型中提取信息?

2024-04-25 21:13:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个基本的django应用程序,它将根据MariaDB数据库中的信息显示当前商店销售额的表格

数据通过一个单独的过程输入数据库,因此它不是在Django中创建的,它只是使用一个简单的python脚本加载一个csv文件并将其解析为一个Insert查询。我的代码中有两个模型,Stores和ShowroomData。Showroomdata保存python脚本中的所有记录,但不保存任何存储信息。我希望它能够显示所有展厅数据以及未存储在展厅数据模型中的商店位置标题。我知道我需要分离模型,但不知道如何将它们链接在一起



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()

我希望它能够输出如下表:

StoreID-位置-日期-时间-销售-税务

这是我的WIP html文件

<!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>

Tags: 数据name脚本信息数据库fieldmodelshtml
1条回答
网友
1楼 · 发布于 2024-04-25 21:13:01

ShowroomData模型上的storeid字段实际上是一个外键。因此,您应声明如下:

class ShowroomData(models.Model):
    store = models.ForeignKey("Stores", db_column="storeid")

现在,您可以在模板中跟随该fk。假设current_showroom是ShowroomData实例的查询集:

        {% for store in current_showroom %}
          <tr>
            <td>{{ store.storeid }}</td>
            <td>{{ store.store.name }}</td>
          </tr>
        {% endfor %}

相关问题 更多 >