0
 AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')

 class Friend(models.Model):
     """ Model to represent Friendships """
     to_user = models.ForeignKey(AUTH_USER_MODEL, related_name='friends')
     from_user = models.ForeignKey(AUTH_USER_MODEL, related_name='_unused_friend_relation')
     created = models.DateTimeField(default=timezone.now)

     objects = FriendshipManager()

     class Meta:
         verbose_name = _('Friend')
         verbose_name_plural = _('Friends')
         unique_together = ('from_user', 'to_user')

     def __unicode__(self):
         return "User #%d is friends with #%d" % (self.to_user_id, self.from_user_id)



 class FriendshipManager(models.Manager):

     def unread_requests(self, user):
         """ Return a list of unread friendship requests """
         key = cache_key('unread_requests', user.pk)
         unread_requests = cache.get(key)

         if unread_requests is None:
             qs = FriendshipRequest.objects.select_related(depth=1).filter(
                 to_user=user,
            viewed__isnull=True).all()
             unread_requests = list(qs)
             cache.set(key, unread_requests)

         return unread_requests

 class Person(models.Model):

     user = models.ForeignKey(User))
     name = models.CharField(max_length=30, blank=True)
     image = models.ImageField(upload_to='photos', blank=True)


     def __unicode__(self):
    return self.user.username

我正在使用这种友谊模型。此模型允许您在用户之间创建朋友。我还有一个名为 Profile 的 UserProfile 模型,位于上面。

以下命令显示如何查看特定用户的所有友谊请求

 >>> user = User.objects.get(pk=1)
 >>> user1 = User.objects.get(pk=1)
 >>> user2 = User.objects.get(pk=2)
 >>> user3 = User.objects.get(pk=3)
 >>> Friend.objects.add_friend(user1,user3)
 <FriendshipRequest: User #1 friendship requested #3>
 >>> Friend.objects.add_friend(user2,user3)
 <FriendshipRequest: User #2 friendship requested #3>
 >>> requests = Friend.objects.unread_requests(user=user3)
 >>> requests
 [<FriendshipRequest: User #1 friendship requested #3>, <FriendshipRequest: User
 #2 friendship requested #3>]
 >>> requests[0].to_user
 <User: hello>

我正在尝试使用图像显示特定用户的所有友谊请求但是

我现在不能这样做,因为请求是在元组中的(下面是一个例子)。

我希望能够检索为特定用户请求友谊的所有用户

然后使用这些用户检索他们的用户 UserProfile 模型引用 Person 以便我可以在模板中显示他们的图像

以最简单的形式

如何检索所有请求友谊的用户(下面的示例是我可以查看一个用户的用户名

     >>> requests = Friend.objects.unread_requests(user=user3)
     >>> requests
     [<FriendshipRequest: User #1 friendship requested #3>, <FriendshipRequest: User
     #2 friendship requested #3>]
      >>> requests[0].to_user

然后收集他们的 UserProfile ( Person )

   Person.objects.filter ( ? )
4

1 回答 1

1

创建好友列表

list_of_friend_requests = [r.to_user for r in requests]

使用django 的过滤进行过滤

persons = Person.objects.filter(user__in=list_of_friend_requests)
于 2013-07-23T21:21:35.980 回答