【问题标题】:Django - Update multiple models from one view (form-table)Django - 从一个视图更新多个模型(表格)
【发布时间】:2017-11-23 20:19:27
【问题描述】:

我有这三个类

class Product(models.Model):
    name        = models.CharField(max_length=50)

class Input(models.Model):
    idProduct   = models.ForeignKey('Product', on_delete=models.CASCADE)
    quantity    = models.IntegerField()
    price       = models.DecimalField(max_digits=5, decimal_places=2)
    created_at  = models.DateTimeField(auto_now=True)

class Output(models.Model):
    idProduct   = models.ForeignKey('Product', on_delete=models.CASCADE)
    quantity    = models.IntegerField()
    created_at  = models.DateTimeField(auto_now=True)

我想用这样的表格制作一个视图/表单

| output-quantity->product  | product-name | input-quantity->product |

列出数据库中的所有产品并添加每个产品的数量(输入或输出)

然后,我将输入和输出相加,然后将它们相减以获得每种产品的库存记录。

我的问题是我不明白如何在视图/表单中同时使用三个模型

【问题讨论】:

  • 到目前为止你尝试过什么?请出示您的查看代码。
  • 你可以,你能在这里分享你的观点吗
  • 我不知道该怎么做。我在网上没有找到在同一视图中使用多个模型的示例

标签: python django django-models django-forms django-views


【解决方案1】:

要访问视图中的模型,您只需像这样导入它们(前提是您遵循 Django 结构):from .models import Product, Input, Output。您现在可以访问模型了。

现在使用诸如Products.objects.all() 之类的函数来获取您想要的数据,例如该命令将返回保存在您的数据库中的所有产品对象。有关 Django 查询的更多信息,请阅读此处:https://docs.djangoproject.com/en/1.11/topics/db/queries/

【讨论】:

  • 感谢您的输入,我想我现在明白了select product.name, SUM(input.quantity) - SUM(output.quantity) as Stock from product join input ON (product.id=input.idProduct) join output ON (product.id=output.idProduct) group by product.name order by product.name 我必须将此 sql 翻译为 django orm。小问题理解:select_related、annotate、aggregate
  • 我认为您可以使用基本的过滤器和获取语句到达您想要的位置,尝试将 SQL 分解成块以使其更容易处理。 Select_related 预填充任何外键,因此在尝试访问它们时不必重新查询,从而提高性能。
猜你喜欢
  • 2011-08-09
  • 2020-04-09
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多