以下是我的模特。
class User(models.Model):
name = models.CharField(max_length = 255)
alias = models.CharField(max_length = 255)
email = models.CharField(max_length = 255)
password = models.CharField(max_length = 255)
confirm_password = models.CharField(max_length = 255)
birthday = models.DateTimeField(null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
friend = models.ManyToManyField('self')
objects = UserManager()
以下作品可以添加朋友。
def add_friend(request, friend_id):
new_friend = User.objects.get(id=friend_id)
print(new_friend.name)
current_user = User.objects.get(id=request.session['user_id'])
print(current_user.name)
current_user.friend.add(new_friend)
current_user.save()
new_friend.friend.add(current_user)
return redirect('/friends/')
但是,我需要帮助从用户中删除朋友。以下是我尝试但它不起作用。当我检查sqllite时,朋友仍然附加到该用户。
def remove_friend(request, friend_id):
remove_friend = User.objects.get(id=friend_id)
print(remove_friend.name)
current_user = User.objects.get(id=request.session['user_id'])
print(current_user.name)
current_user.friend.remove(remove_friend)
current_user.save()
remove_friend.friend.remove(current_user)
return redirect('/friends/')