【问题标题】:Django add friends to queryDjango加好友查询
【发布时间】:2013-04-24 20:14:16
【问题描述】:

我正在尝试创建一个查询,在其中检索已登录用户及其“朋友”的所有“活动”,按最近排序。 (使用 Django-Simple-Friends 连接朋友)。

以下查询非常适合检索按最近排序的登录用户的所有活动,但我不确定如何还包括用户的连接“朋友”。

activity = Activity.objects.filter(user=request.user).order_by('-created_date')

我的活动课是:

class Activity(models.Model):
    user = models.ForeignKey(User)
    created_date = models.DateTimeField(default=datetime.now)
    activity_type = models.IntegerField(default=0) 

我很感激时间和专业知识。

【问题讨论】:

  • 用户的连接好友存储在哪个表中?
  • 用户的连接好友存储在 Django-Simple-Friends 创建的“friendship”表中

标签: django django-queryset


【解决方案1】:

以这种方式尝试查询:

friend_user_list = list(friends_list) + [request.user]
activity = Activity.objects.filter(user__in=friend_user_list).order_by('-created_date')

我想要做的是连接列表,[request.user] 和他们的朋友列表(假设friends 是友谊关系的相关名称)和user__in 应该修改 WHERE 条件允许列表中的所有用户满足查询。

希望对你有帮助。

【讨论】:

  • 我收到错误消息:'User' 对象没有属性'friends' 我也尝试使用“friendship”代替“friends”,但收到错误消息:'Friendship' 对象没有属性'对我可以尝试什么有什么想法吗?
  • 您通常如何为用户获取好友?
  • 我还不需要生成那个列表,但是文档给出了这个例子来获取所有用户的朋友:friends = Friendship.objects.friends_of(user1)
  • 好吧,我尝试对查询执行的操作是将列表与用户及其朋友保持一致。然后,使用 __in 访问器将其传递给过滤器函数。你可以试试这个:user__in=[request.user]+Friendship.objects.friends_of(request.user) 在过滤器中。
  • 我认为这已经非常接近了。如果我传入 user__in=[request.user] 或 user__in=Friendship.objects.friends_of(request.user) 我可以工作 我应该尝试在查询之外创建一个列表然后传入该列表吗? (我对编程还很陌生,所以我并不总是确定最佳方法)
猜你喜欢
  • 2015-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-16
  • 1970-01-01
相关资源
最近更新 更多