我有一个User对象和一个Connection对象来管理用户之间的连接。
class User:
username = models.CharField(max_length=100,)
和
class Connection:
user = models.ForeignKey(User)
friend = models.ManyToManyField('self', related_name="_friends", symmetrical=True)
followers = models.ManyToManyField('self', related_name="_followers", symmetrical=False)
following = models.ManyToManyField('self', related_name="_following", symmetrical=False)
我不确定如何在此建模中添加朋友。
user.connection_set._friends.add(target) -> does this work?
有人可以帮我吗?
答案 0 :(得分:1)
使用OneToOne(我想您的用户只有一个与多个关注者,朋友等的连接?)
如果您使用FK或m2m字段,则需要再一步找到要使用的连接(例如User.objects.get(XXXX).connection.get(XXXX)
class User:
username = models.CharField(max_length=100,)
class Connection:
user = models.OneToOneField(User)
friend = models.ManyToManyField('self', related_name="_friends", symmetrical=True)
followers = models.ManyToManyField('self', related_name="_followers", symmetrical=False)
following = models.ManyToManyField('self', related_name="_following", symmetrical=False)
user = User.objects.last()
user_to_add = User.objects.first()
user.connection.followers.add(user_to_add)