0

I need to make a table 'Friend' with foreignkeys that store instances of the User class- two of them one for the friend and one for the user attribute. (Table is of relationships)

How to do this? OnetoOneField doesn;t work. It gives me an error in the terminal if I try to make both of them keys. So this is two Many to Many relationships from User to Friend.

If it's impossible, what is a better way to set this up? Can the User table have a One-to-Many relationship to itself?

class Friend(models.Model):
    id = models.IntegerField(primary_key=True)
    friend_id= models.ForeignKey(User, null=False)
    user_id = models.ForeignKey(User, null=False)
V. Snow
  • 133
  • 1
  • 14
  • Actually a many-to-many ralation creates a new mapping table with two foreign keys, in the background. So if you don't want to replace the User class you approach look good. – Klaus D. Aug 30 '17 at 22:31

2 Answers2

0

You've probably seen this error while trying to make migrations:

appname.Friend.friend_id: (fields.E305) Reverse query name for 'Friend.friend_id' clashes with reverse query name for 'Friend.user_id'.
        HINT: Add or change a related_name argument to the definition for 'Friend.friend_id' or 'Friend.user_id'

It clearly tells, that you should add the related_name argument:

class Friend(models.Model):
    friend_id = models.ManyToManyField(settings.AUTH_USER_MODEL)
    user_id = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='user_id')

Here is Django docs page about the best practices on customizing and extending the exicting User model.

d2718nis
  • 1,279
  • 9
  • 13
0

My suggestion would be to create a new User class inheriting from django's user and in it you would create friends as many to many from User.

from django.contrib.auth.models import AbstractUser
from django.db.models import CharField, ManyToManyField
from django.utils.translation import ugettext_lazy as _

class User(AbstractUser):
    name = CharField(_("Name of User"), blank=True, max_length=255)
    friends = ManyToManyField('self', related_name='friends')
  • 1
    Rather than posting several distinct answers on the same question, [edit your first answer](https://stackoverflow.com/posts/45970593/edit) and add all the info from your other answers there. – Das_Geek Nov 19 '19 at 14:23