简体   繁体   中英

django model field depend on the value of another field

The use case of my application is I will have various fields to fill and among them one is Industry field and another is Segment Field for brand. The industry field is like category that brand falls into. So, if i choose the industry as Health Care for XYZ brand then the segment field should show the items like 'Ayurveda', 'Dental Clinics' (all health care related items). Basically, its like sub-category.

Here is a sample model

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

This is a simple model and I have not created Segment model as I am not sure how to approach to this problem. I am just curios to know, if for such case, do i have to something special in models.py or in the view side. Such type of things get arise during development phase, thus, I want to be clear on problem solving pattern in django.

UPDATE

https://www.franchisebazar.com/franchisor-registration here if you choose industry inside Business model section, the segment will be updated accordingly.

You can have a 3 model design like

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)

You need to define relations between your models. You can find documentation about ManyToMany relation here which is suitable in your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM