Django中的ManyToMany Relationship“add-friend,remove-friend”无法正常工作

问题描述 投票:1回答:1

我该如何解决这个多对多的关系问题。我正在建立像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 Shell返回:<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

python django python-3.x django-models manytomanyfield
1个回答
1
投票

由于“friends”是Profiles之间的多对多关系,因此您可以将您的字段恢复到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

© www.soinside.com 2019 - 2024. All rights reserved.