简体   繁体   中英

How to Save multiselect in django model?

I have two model Business and Category. I want to save Multiple categories in Business.

class Business(models.Model):
    user = models.ForeignKey('User', on_delete=models.CASCADE)
    business_name = models.CharField(max_length=100)
    category = models.IntegerField()
    keyword = models.CharField(max_length=100)

and Category Model Is Here

class Category(models.Model):
    name = models.CharField(max_length=100)
    slug = models.CharField(max_length=100)

Category Model is already filled with values.

you have two option for that 1) many to one, 2) many to many 1) many to one is ForeignKey to add in category model and link each category with business, in this you can identify which category is child of buisness, you can find more details in django document

class Category(models.Model):
    name = models.CharField(max_length=100)
    slug = models.CharField(max_length=100)
    business = models.ForeignKey(Business, on_delete=models.CASCADE)

2) many to many is select multiple category in business, and you can access all thing in business model and in you write query on business model and access to also category for that you need write category before buisness, you can find more detail in django document

class Business(models.Model):
    user = models.ForeignKey('User', on_delete=models.CASCADE)
    business_name = models.CharField(max_length=100)
    category = models.IntegerField()
    keyword = models.CharField(max_length=100)
    category= models.ManyToManyField(Category)

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