Search code examples
pythondjangodjango-modelsdjango-mptt

Django mptt Multiple references to class objects


I need to make a model for spices. Some spices may consist of others, or be basic. I need something like TreeForeignKey with multi-select option. I tried to use TreeManyToManyField, but I can't set null for base spices there. Here is my code:

class Goods(MPTTModel):
    category = models.ForeignKey(Category,
                                 related_name='goods',
                                 on_delete=models.SET_NULL,
                                 null=True)    
    name = models.CharField(max_length=150, db_index=True)
    parent = TreeManyToManyField(
        'self',
        blank=True,)

Solution

  • An MPTT isn't a good fit for what you are asking. In a tree, each node has only 1 parent (or no parent for a root node). But, in your case:

    • A combination spice could be made of many base spices
    • A base spice could be used in many combination spices

    This is a many-to-many relationship. See https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_many/

    Your model could look something like:

    class Spice(models.Model):
        ingredients = models.ManyToManyField("self", blank=True)