Furry Bear
Furry Bear

Reputation: 27

Django, How to make symmetric relationship between self with extra field?

I had a model in symmetric relationship:

 class person(models.Model):
    name = models.CharField(max_length=20)
    friends = models.ManyToManyField('self', blank= True)

And I need a extra field to explain their relationship, for example: they be friend since 1980.

be_friend_since = models.DateField(blank = True)

How to add this extra field in my models? Thanks! :)

Upvotes: 1

Views: 378

Answers (1)

Selcuk
Selcuk

Reputation: 59315

You must use a through table to include that field, such as:

class Person(models.Model):
    name = models.CharField(max_length=20)
    friends = models.ManyToManyField('self', through='Friendship', blank=True)

class Friendship(models.Model):
    person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='+')
    friend = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='+')
    friends_since = models.DateField(blank=True)

Upvotes: 1

Related Questions