【问题标题】:django model field depend on the value of another fielddjango模型字段依赖于另一个字段的值
【发布时间】:2019-02-16 14:14:15
【问题描述】:

我的应用程序的用例是我要填写多个字段,其中一个是行业字段,另一个是品牌的细分字段。行业领域就像品牌所属的类别。所以,如果我选择industryHealth CareXYZ brand,那么segment 字段应显示“阿育吠陀”、“牙科诊所”等项目(所有与医疗保健相关的项目)。基本上,它就像子类别。

这是一个示例模型

class Industry(models.Model):
    name = models.CharField(max_length=150, blank=True, null=True)

    class Meta:
        verbose_name = 'Industry'
        verbose_name_plural = 'Industries'

    def __str__(self):
        return self.name



class Segment(models.Model):
    industry = models.ForeignKey(Industry, related_name='segment', on_delete=models.CASCADE)
    name = models.CharField(max_length=150, blank=True, null=True)

    class Meta:
        verbose_name = 'Segment'
        verbose_name_plural = 'Segments'

    def __str__(self):
        return f'{self.industry.name} - {self.name}'


class BusinessModel(models):
    industry = models.ForeignKey(Industry, blank=False, null=False, related_name='industry', on_delete=models.CASCADE)
    # segements = models.ForeignKey()
    total_investment = models.CharField() # will be choice field

这是一个简单的模型,我还没有创建分段模型,因为我不确定如何解决这个问题。我只是好奇地知道,如果在这种情况下,我是否必须在models.py 或视图方面做一些特别的事情。在开发阶段会出现这种类型的事情,因此,我想弄清楚 django 中的问题解决模式。

更新

https://www.franchisebazar.com/franchisor-registration这里如果您在商业模式部分选择行业,该部分将相应更新。

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    你可以有一个 3 模型设计像

    class Industry(models.Model):
        name = models.CharField(max_length=150, blank=True, null=True)
    
    class Segment(models.Model):
        name = models.CharField(max_length=150, blank=True, null=True)
    
    class Mapping(models.Model):
         industry = models.ForeignKey(Industry)
         segment = models.ForeignKey(Segment)
    

    【讨论】:

    • 所以映射应该是BusinessModel表中的外键而不是单独的Industry和Segment表?
    • 我不明白你的问题。 Mapping 是一个关联实体,关联 Industy 和 Segment en.wikipedia.org/wiki/Associative_entity
    • 我会调查的,谢谢。同时,该关联实体是否像多对多?
    • 是的,多对多将在引擎盖下创建一个关联实体。如果您需要跟踪有关关系本身的信息,您需要将其添加为它自己的模型。取决于你在做什么。
    【解决方案2】:

    您需要定义模型之间的关系。您可以找到适用于您的情况的有关 ManyToMany 关系 here 的文档。

    【讨论】:

    • 商业模式应该只属于一个行业,行业有多个细分市场,但商业模式里面的细分市场只有一个。我的意思是,如果我选择了医疗保健,那么它有多个细分市场,但从这些细分市场中,我只能选择一个值。
    猜你喜欢
    • 2019-03-11
    • 2012-05-20
    • 2012-03-23
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 2019-08-27
    • 2015-09-26
    相关资源
    最近更新 更多