【问题标题】:How to get a django template to pull information from two different models?如何获取 django 模板以从两个不同的模型中提取信息?
【发布时间】:2019-06-15 07:45:23
【问题描述】:

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

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



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>

【问题讨论】:

    标签: python mysql sql django mariadb


    【解决方案1】:

    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 %}
    

    【讨论】:

      猜你喜欢
      • 2014-03-26
      • 2018-07-24
      • 2021-10-02
      • 2021-02-26
      • 2018-07-21
      • 2012-11-22
      • 2020-07-17
      • 2017-09-14
      相关资源
      最近更新 更多