我如何解决这么多对多的关系问题。我正在构建一个像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)
从管理员的配置文件中选择两个用户以创建与超级用户的关系并保存后。
当我访问 shell 尝试以下命令时,出现了两个问题:
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())
壳牌返回:
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
由于"friends"是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")
https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.ManyToManyField.symmetrical