python - 在帖子列表中显示用户帖子

标签 python django

以下方法返回我关注的用户帖子的查询集。

def get_queryset(self, *args, **kwargs):

    # returns the users that i follow
    following_users = self.request.user.profile.get_following() 

    #gets posts of following users
    qs = Tweet.objects.filter(user__in=following_users).order_by("-timestamp") 

    return qs

我也想在此查询集中添加我自己的帖子。如何在此查询集中添加我自己的用户?

像这样:

def get_queryset(self, *args, **kwargs):

    # returns the users that i follow
    following_users = self.request.user.profile.get_following() 

    following_users.append(self.request.user) # This is not working

    #gets posts of following users
    qs = Tweet.objects.filter(user__in=following_users).order_by("-timestamp") 

    return qs

像这样>我应该怎么做?

我是初学者,请帮忙。

最佳答案

这不起作用的原因是,可能 get_following() 返回一个 QuerySet,而不是一个列表,并且您不能附加到 Queryset.

可能更容易用析取条件来实现:

from django.db.models import <b>Q</b>

def get_queryset(self, *args, **kwargs):
    following_users = self.request.user.profile.get_following()
    return Tweet.objects.filter(
        <b>Q(</b>user__in=following_users<b>) |</b>
        <b>Q(user=self.request.user)</b>
     ).order_by('-timestamp')

关于python - 在帖子列表中显示用户帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58936389/

相关文章:

Python梯度下降-成本不断增加

django - Dockerized Django REST Framework/Postgresql - 不允许的主机

python - 如何从 django.utils.safestring.SafeText 获取字符串

python - 在 Django 中显示漂亮的代码

python - django 中的自定义用户仪表板

python - Tensorflow:在时间流中的索引处查找张量

python - 根据值的重复对列表元素进行分组

python - Setup.py:如何添加外部安装候选项?

django - 如何使用 Django 保存到远程服务器

python - 有关 “Ignoring visible gpu device and Adding visible gpu device”的问题