我正在实现一个类似于facebook的朋友系统,人们可以发送友谊请求,接受请求,然后看到他们的朋友。在看到朋友请求的页面上,我试图过滤掉已经接受朋友请求并且现在已经是朋友的用户。在下面的代码中,'u'是当前登录的用户。友情表有两个字段,都是外键,请看下面:
try:
already_friends = Friendship.objects.get(Q(from_friend=u) | Q(to_friend=u))
for x in already_friends.iterator():
my_requests = FriendRequest.objects.filter(Q(receiver=request.user) & ~Q(sender=x))
except ObjectDoesNotExist:
class FriendRequest(models.Model):
sender = models.ForeignKey(User, related_name='the_sender',on_delete=models.CASCADE)
receiver = models.ForeignKey(User, related_name='the_receiver', on_delete=models.CASCADE)
def __str__(self):
return "request sent"
class Meta:
unique_together = (('sender', 'receiver'),)
class Friendship(models.Model):
from_friend = models.ForeignKey(User, related_name="from_friend", on_delete=models.CASCADE)
to_friend= models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return "Friend request accepted"
class Meta:
unique_together = (('from_friend', 'to_friend'),)
当我使用Q(复杂查询)在顶部编写的查询,然后使用迭代器时,我得到以下错误:
'Friendship' object has no attribute 'iterator'
我怎么能实现我打算做什么使用django模型/查询?
您应该使用.filter(…)
[Django-doc] not.get(…)
[Django-doc]:.get(…)
检索一个单个Friendship
对象,如果没有这样的对象,或者如果有多个对象,将引发错误。另一方面,.filter(…)
将返回满足给定谓词的所有Friendship
记录的查询集(可能为空):
already_friends = Friendship.objects.filter(Q(from_friend=u) | Q(to_friend=u))
for x in already_friends.iterator():
my_requests = FriendRequest.objects.filter(Q(receiver=request.user) & ~Q(sender=x))
此外,使用Q(sender=x)
也没有意义:x
是Friendship
对象,而不是用户对象。您可能想要检查from_friend_id
或to_friend_id
是否为u
,从而使用另一个进行过滤。比如:
already_friends = Friendship.objects.filter(Q(from_friend=u) | Q(to_friend=u))
for x in already_friends.iterator():
if x.from_user_id = u.id:
my_requests = FriendRequest.objects.filter(receiver=request.user, sender_id=x.to_user_id)
else:
my_requests = FriendRequest.objects.filter(receiver=request.user, sender_id=x.from_user_id)