首页 > 解决方案 > 当并非在所有情况下都需要所有字段时,如何为用户输入构建 django 模型

问题描述

我正在使用新功能扩展现有的 django 应用程序。问题基本上如下。

抱歉,如果已经提出了与此问题相当的问题,我不确定要搜索什么来找到解决方案。

我有一个“商店”模型,其中包含与“部门”模型的多对多关系,并非所有商店都有相同的部门。

我需要跟踪每个商店的每日部门数量,并且我需要一个用户表单来输入所有这些信息。

我不知道是否应该创建一个包含所有可能部门的模型,或者是否应该创建一个具有一个部门和权重的模型,然后每天创建与部门一样多的对象。

此应用程序中的扩展能力将非常重要,我想从正确的开始。

代码如下。

店铺部门

class Department(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255, unique = True)
    short_name = models.CharField(max_length=32)
    description = models.CharField(max_length=255)
    def __str__(self):
            return self.name;

体积数据选项(有问题的模型)

选项 1,一个模型,一切:

class VolumeData(models.Model):
    id = models.AutoField(primary_key=True)
    store = models.ForeignKey(stores.models.Store, on_delete=models.DO_NOTHING)
    date = models.DateField(auto_now_add=True,null=False,blank=False)
    produce = models.DecimalField(decimal_places=2,Null=True)
    dairy = models.DecimalField(decimal_places=2,Null=True)
    deli = models.DecimalField(decimal_places=2,Null=True)
    meat = models.DecimalField(decimal_places=2,Null=True)
    seafood = models.DecimalField(decimal_places=2,Null=True)
    coffee = models.DecimalField(decimal_places=2,Null=True)
    frozen = models.DecimalField(decimal_places=2,Null=True)

选项 2,一个模型,但我需要更多对象。

class VolumeData(models.Model):
    id = models.AutoField(primary_key=True)
    store = models.ForeignKey(stores.models.Store, on_delete=models.DO_NOTHING)
    date = models.DateField(auto_now_add=True,null=False,blank=False)
    department = ForeignKey(Departmnet, blank=False)

我觉得选项 2 会更灵活,但我担心它会创建的额外对象的数量。

然而,选项 1 会有很多我不需要的空值,我不确定这是否更糟,它也会在部门中烘烤,这可能很复杂?

部门列表不会很动态,我预计每年更新一次少于一次,最终用户不太可能需要修改该信息。

标签: pythondjangomodel

解决方案


我也喜欢选项 2,但我认为您需要更进一步,为每个部门销售的不同商品创建一个类:

class Items(models.Model):
    id = models.AutoField(primary_key=True)
    product_SKU = models.CharField(max_length=15) # set max_length as needed
    product_name = models.CharField(max_length=50) # set max_length as needed
    number_sold = models.DecimalField(decimal_places=2,Null=True)

有了这些增加的信息深度,您将能够结合更深层次的报告、人工智能预测、机器学习等。这只是我的两分钱。


推荐阅读