1

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! :)

doru
  • 9,022
  • 2
  • 33
  • 43
Furry Bear
  • 27
  • 4
  • 1
    Use a new `Relationship` model, that serves as an intermediate table (with a `through` keyword) for friendship between persons. See eg https://stackoverflow.com/questions/4443190/djangos-manytomany-relationship-with-additional-fields –  Sep 11 '17 at 08:30

1 Answers1

1

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)
Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • 1
    this will error as "Many-to-many fields with intermediate tables must not be symmetrical". The trick is to still set it up with symmetrical=False, but it can be used as symmetrical. check this https://charlesleifer.com/blog/self-referencing-many-many-through/ https://www.caktusgroup.com/blog/2009/08/14/creating-recursive-symmetrical-many-to-many-relationships-in-django/ – xjlin0 Sep 13 '19 at 17:31