python - Django 根据之前的查询选择数据库对象

标签 python sql django orm models

我目前正在开发一个项目,其中有 Twitter 风格的单向关注,但我无法弄清楚如何根据用户关注的人在数据库中选择“帖子”。

我正在使用默认用户功能,这是我的以下模型:

class Following(models.Model):
    user = models.ForeignKey(User, related_name="user")
    following = models.ForeignKey(User, related_name="following")

和我的帖子模型:

class Post(models.Model):
    title = models.CharField(max_length=100)
    text = models.TextField()
    user = models.ForeignKey(User)
    date_time = models.DateTimeField(auto_now=True)

最后,我认为我正在努力开始工作的片段:

def home(request):
    following = Following.objects.filter(user=request.user)
    posts = Post.objects.filter(/*not sure what to put here*/)

我整晚都在努力让这个工作正常进行,但我确实找不到解决方案,所以任何帮助都会很棒。

如果您可能需要查看我未在此处发布的任何内容,github repository for this project is here

最佳答案

我的 django 已经生锈了,但是这里是:

posts = Post.objects.filter(user__following__user=request.user)

关于python - Django 根据之前的查询选择数据库对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7133194/

相关文章:

Sql Server 相当于 COUNTIF 聚合函数

sql - 将日期插入SQLite表

python - Django 将自定义表单参数传递给 Formset

python - Pandas 交叉制表和计数

python - tqdm可以嵌入html吗?

Python正则表达式多次匹配

MySQL如何GROUP BY计数列?

Django:相关名称属性(数据库错误)

python - Django/PostgreSQL 全文搜索 - 在 AWS RDS PostgreSQL 上使用 SearchVector 与 SearchVectorField 时的不同搜索结果

python - 寻找曲线下的最大面积 | Pandas ,matplotlib