2

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)
Inversus
  • 3,125
  • 4
  • 32
  • 37
  • 2
    Note that the ForeignKey indicates a *parent* relationship, not a child one, since it can only point to one element. So it should be called something like "parent_component" and the related_name can be "subcomponents". – Daniel Roseman Jul 13 '18 at 18:21
  • @scharette yes please – Inversus Jul 13 '18 at 18:26
  • Possible duplicate of [Can I Make a foreignKey to same model in django?](https://stackoverflow.com/questions/11214175/can-i-make-a-foreignkey-to-same-model-in-django) – Dap Jul 13 '18 at 18:28

1 Answers1

3

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')
scharette
  • 9,437
  • 8
  • 33
  • 67
  • I tried this and got the error: `django.db.utils.OperationalError: no such table: Monitor_monitoredcomponent` – Inversus Jul 13 '18 at 18:24
  • (the actual class name is MonitoredComponent, and it's in a django app called Monitor, that's why it's Monitor_monitoredcomponent) – Inversus Jul 13 '18 at 18:27
  • this is the correct answer. this is also a repost of this question https://stackoverflow.com/questions/11214175/can-i-make-a-foreignkey-to-same-model-in-django. that error is likely the cause of your models and database being out of sync or other migration issues. try python manage.py migrate – Dap Jul 13 '18 at 18:28
  • @Dap I did not know this answer was written, but instead of posting it in a comment of m answer propose a duplicate flag which is more appropriate. – scharette Jul 13 '18 at 18:29
  • @Dap I just ran python manage.py migrate again and there are no migrations to apply – Inversus Jul 13 '18 at 18:30
  • Can you please add Daniel Roseman's suggestion to your answer? I'm not sure how that would be implemented – Inversus Jul 13 '18 at 18:33