[Django]-Django related key of the same model

8πŸ‘

βœ…

It is common to add a foreign key to self as such:

class Item(models.Model):
    parent = models.ForeignKey('self')

You may specify a related name as such:

class Item(models.Model):
    parent = models.ForeignKey('self', related_name='children')

Because an Item may not have a parent, don’t forget null=True and blank=True as such:

class Item(models.Model):
    parent = models.ForeignKey('self', related_name='children', null=True, blank=True)

Then you will be able to query children as such:

item.children

You might as well use django-mptt and benefit of some optimization and extra tree features:

from mptt.models import MPTTModel, TreeForeignKey

class Item(MPTTModel):
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
πŸ‘€jpic

0πŸ‘

πŸ‘€Niklas

-1πŸ‘

You would use foregein key in the same model if and only if you use string.

class Item(models.Model):
  foo = models.ForeignKey("reposted_from")

class reposted_from(models.Model):
  repost_from = models.CharField(max_length=122)

for example.

Otherwise, you will get undefined reference.
Is that what you need?

πŸ‘€CppLearner

Leave a comment