Search code examples
pythondjangolistdata-structuresmodels

Django field with multiple values and multiple owners


I am struggling with the concept with a very join-ed relationship. I want to have something like:

class Category(models.Model):
    name = models.CharField(max_length=128, unique=True)
    descriptions = models.Listfield? #or something like this

class Descriptions(models.Model):
    name = models.CharField(max_length=128, unique=True)
    categories = models.Listfield? #or something like this

the idea is that categories will have descriptions that you can click that will give you a list of categories with that description, and vice versa. So if categories were like [Elephant, Truck, Tree] and descriptions were like [Heavy, Trunk], I'd want it set up so Elephant.descriptions = [Heavy, Trunk] and Heavy.categories = [Elephant, Truck]


Solution

  • 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/