我正在尝试创建一个django应用,其中一个用户可以将其他用户添加为朋友。这就是我做的,
models.py
,
class Friend(models.Model):
users = models.ManyToManyField(User)
current_user = models.ForeignKey(User, related_name='all', null=True)
views.py
# view for adding or removing friends
def change_friends(request, pk):
new_friend = User.objects.get(pk=pk)
data = Friend.objects.get(current_user=request.user)
frnds = data.users.all()
new_friend in frnds:
data.users.remove(new_friend)
else:
data.users.add(new_friend)
redirect(request.META['HTTP_REFERER'])
# Displaying frinends,
def following(request, id=None):
my_friend, created = Friend.objects.get_or_create(current_user_id=id)
all_friends = my_friend.users.all()
return render(request, 'all/follow.html', {'all_friends': all_friends})
此代码工作正常,直到我只添加了1个帐户的朋友,但当我从多个帐户添加了几个朋友时,它开始显示错误get() returned more than one Friend -- it returned 2!
。
我们如何解决这个问题?谢谢!
答案 0 :(得分:0)
删除管理员中的所有朋友实例并将模型更改为:
class Friend(models.Model):
users = models.ManyToManyField(User)
current_user = models.OneToOne(User, related_name='friend', on_delete=models.CASCADE, null=True)
那么观点应该是:
# view for adding or removing friends
def change_friends(request, pk):
new_friend = User.objects.get(pk=pk)
friends = request.user.friend.users.all()
new_friend in friends:
request.user.users.remove(new_friend)
else:
request.user.users.add(new_friend)
redirect(request.META['HTTP_REFERER'])
# Displaying frinends,
def following(request, id=None):
my_friend, created = Friend.objects.get_or_create(current_user_id=id)
all_friends = my_friend.users.all()
return render(request, 'all/follow.html', {'all_friends': all_friends})
如果您使用many_to_many
来记录朋友关系,最好将模型设置为:
current(OneToOne) users(ManyToMany)
如果您使用ForeignKey
来记录朋友关系,最好将模型设置为:
current(ForeignKey) user(ForeignKey)
<强>更新强> 如果您无法再更改模型,只需将代码更改为:
def change_friends(request, pk):
new_friend = User.objects.get(pk=pk)
data = Friend.objects.filter(current_user=request.user)
has_user = False
for x in data:
if new_friend in x.users.all():
has_user = True
x.users.remove(new_friend)
if not has_user:
firend = Friend.objects.filter(current_user=request.user).first()
if friend:
friend.users.add(new_friend)
else:
friend = Friend.objects.create(current_user=request.user)
friend.users.add(new_friend)
redirect(request.META['HTTP_REFERER'])
答案 1 :(得分:0)
在更改好友功能中,这行代码会像这样改变
new_friend = User.objects.filter(pk=pk).first()
试试这个......