[Django]-What is the use of recursive relationship and a relationship to an undefined model in Django?

3๐Ÿ‘

โœ…

You can use it to create links to other objects of this Model.

For example if you have many members in a website and each has an inviter (also of Member type) you can do the following:

class Member(Model):
    inviter = models.ForeignKey(
        'self',
        related_name="invited_set"
    )

If you want the inviter, you do:

Member.objects.get(id__exact=5).inviter

If you want all members that this member has invited you use:

Member.objects.get(id__exact=5).invited_set
๐Ÿ‘คLycha

1๐Ÿ‘

For models not yet defined:

class Gallery(models.Model):
    title_image = models.ForeignKey('Image')

class Image(models.Model):
    part_of = models.ForeignKey(Gallery)

since these classes refer to each other, at least one of them needs to refer to a class not yet defined.

๐Ÿ‘คsecond

Leave a comment