1👍
✅
You could use a ManyToManyField
since it’s a many to many relationship (one category can be associated with many descriptions and one description can be associated with many categories
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
class Description(models.Model):
name = models.CharField(max_length=128, unique=True)
categories = models.ManyToManyField(Category, blank=True)
With this method you only need to add the ManyToManyField
in one of the models, either Descriptions or Categories.
you then could do the following:
new_cat = Category(name = 'cat1')
new_cat.save()
new_desc = Description(name = 'desc1')
new_desc.save()
new_desc.categories.add(new_cat)
and they would be associated with each other, with no need for a ManyToManyField
in the Category
model
you can then access all the categories associated with new_desc
with:
new_desc.categories.all()
or
new_cat.description_set.all()
for all of the descriptions associated with new_cat.
It will return a QuerySet though, not a list
More info on ManyToManyField
:
https://docs.djangoproject.com/en/1.8/topics/db/examples/many_to_many/
Source:stackexchange.com