pythondjangopython-3.xdjango-modelscontainment

Django - How do I create a model that contains a collection of its own type?


One of the fields in a model I'm creating is for a list of instances of its own type. How do I do this in django? I couldn't find any documentation on how to do this..

This is something like what I am talking about, but doesn't work because the Component class isn't defined yet (and probably for other reasons too).

class Component(models.Model):
    name = models.CharField()
    description = models.CharField()
    status_ok = models.BooleanField()
    subcomponents = models.ForeignKey(Component)

A regular class that briefly demonstrates the concept:

class Component:
    def __init__(self, name, description, status_ok, *subcomponents):
        self.name = name
        self.description = description
        self.status_ok = status_ok
        self.subcomponents = []
        for subcomponent in subcomponents:
            if isinstance(subcomponent, Component):
                self.subcomponents.append(subcomponent)
            else:
                raise TypeError(subcomponent)

Solution

  • To reference the same model use the normal Python syntax self but as a string,

    Class Component(models.Model):
        name = models.CharField()
        description = models.CharField()
        status_ok = models.BooleanField()
        subcomponents = models.ForeignKey('self')