【问题标题】:Show value in table from a model with template in django在 django 中使用模板在表格中显示值
【发布时间】:2020-09-14 15:45:35
【问题描述】:

我想建立一个网站来管理面包生产,但我面临两个问题。

我有一个模型面包 (Pain),它允许我制作面包并为该面包提供起始价格。 (nom_pain = 名称,prix_HT = 价格)

class Pain(models.Model):
nom_pain = models.CharField(max_length=25,primary_key=True)
prix_HT = models.DecimalField(max_digits=4,decimal_places=2)
pain_decouverte = models.BooleanField(null=False)
def __str__(self):
    return '{}'.format(self.nom_pain)

我有一个模型组 (Groupe),它代表不同的客户组。 (nom_groupe = 名称)

class Groupe(models.Model):
nom_groupe = models.CharField(max_length=30)

def __str__(self):
    return '{}'.format(self.nom_groupe)

我希望在一个页面上将每个面包的价格与一组客户匹配,然后将其显示在表格中(在空白单元格中插入面包价格)

            | Bread 1 | Bread 2 | Bread 3 |
    Group 1 |  0.5    |  0.6    |         |      
    Group 2 |   1     |         |   0.5   |
    Group 3 |  0.5    |  0.4    |   0.7   |

我的第一个问题是我无法在我的模型价格(Prix)中保存 2 次组/面包(我希望以组/面包/价格的形式保存)。

第二个问题是我不知道如何在我的模板中显示我的表格图表。我只能显示可用的面包和客户组。

有没有办法做到这一点?

非常感谢您的回答

【问题讨论】:

  • 您需要定义一个多对多字段,其中包含存储价格的直通表。
  • 如何避免模型中的数据重复?
  • 带有UniqueConstraint
  • 我知道你在说什么,但我有一个错误。可能在我的代码中

标签: python django templates model show


【解决方案1】:

您可以在PainGroupe 之间创建一个ManyToManyField。这个ManyToManyFieldthrough=… model [Django-doc]Prix 模型:

class Groupe(models.Model):
    nom = models.CharField(max_length=30, unique=True)

    def __str__(self):
        return self.name

class Pain(models.Model):
    nom = models.CharField(max_length=25, unique=True)
    pain_decouverte = models.BooleanField()
    groupes = models.ManyToManyField('client.Groupe', related_name='pains', through='facturation.PainPrix')

    def __str__(self):
        return self.nom

class PainPrix(models.Model):
    pain = models.ForeignKey('pain.Pain', related_name='prix', on_delete=models.CASCADE)
    groupe = models.ForeignKey('client.Groupe', related_name='prix', on_delete=models.CASCADE)
    prix = models.DecimalField(max_digits=4,decimal_places=2)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['pain', 'groupe'], name='prix_unique')
        ]

【讨论】:

  • 感谢您的回答。当我想迁移时,他不工作。但是在模型 Pain 中我想要“prix_HT”,因为如果模型 Prix 中不存在,我会得到价格
  • @Aomichi:但是如果我理解正确的话,价格取决于Groupe,所以将价格存储在Pain 中毫无意义。如果您想要一个基本价格,您仍然可以添加一个。由于模型的 当前 状态,迁移可能不起作用。删除数据库并从头开始迁移可能是有意义的。
  • 是的,但是所有的groupe不一定有另一个价格(这是为了方便管理,因为有很多例外)。是的,我尝试通过删除数据库和迁移但建立关系时出错
  • @Aomichi:你得到的正是 what 错误?请注意,您最好不要使用nom(或pain_nom)作为主键,因为数据库中的排序规则可能非常麻烦。
  • ImportError: cannot import name 'Pain' from partial initialized module 'pain.models'(很可能是由于循环导入)
猜你喜欢
  • 1970-01-01
  • 2018-11-19
  • 2011-07-10
  • 2017-03-27
  • 2016-09-14
  • 2011-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多