我该如何解决这种多对多关系问题。我正在建立一个类似Facebook的“添加和删除朋友”系统。 “如果A与B成为朋友,那么B与A成为朋友”。
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, null=True)
location = models.CharField(max_length=50, null=True, blank=True)
class Friend(models.Model):
friend_user = models.ManyToManyField(User)
在“管理员”中的“个人资料”中选择两个用户以创建与超级用户的关系并保存后。
访问外壳程序尝试以下命令时,出现两个问题:
from django.contrib.auth.models import User
from accounts.models import Friend
实例化后:
friend = Friend()
当我输入:
friend
壳牌退货:
<Friend: Friend object (None)>
我认为问题出在上面,它不应该返回“无”
此外,当我尝试添加关系时:
friend.friend_user.add(User.objects.last())
Shell返回:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/macadmin/Documents/Django_wapps/fbook/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 498, in __get__
return self.related_manager_cls(instance)
File "/Users/macadmin/Documents/Django_wapps/fbook/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 795, in __init__
(instance, self.pk_field_names[self.source_field_name]))
ValueError: "<Friend: Friend object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used.
任何帮助将不胜感激。
PS:我正在使用本教程:https://www.youtube.com/watch?v=nwpLCa79DUw&list=PLw02n0FEB3E3VSHjyYMcFadtQORvl1Ssj&index=54
答案 0 :(得分:1)
由于“朋友”是Profile
之间的多对多关系,因此您可以将字段带回到Profile类中,并使用字符串"self"
引用相同的模型。
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, null=True)
location = models.CharField(max_length=50, null=True, blank=True)
friends = models.ManyToManyField("self")