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

发布于 2024-11-30 17:20:23 字数 874 浏览 0 评论 0原文

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

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

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存储库在这里

I'm currently working on a project where there is twitter-style one way following, and I've been unable to figure out how to select 'posts' in the database based on who the user is following.

I'm using the default user functionality, and then this is my following model:

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

and my posts model:

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

Finally, the snippet from my view that I'm trying to get to work:

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

I've been trying all night to get this working and I can't really see a solution, so any help would be awesome.

if there's anything that you might need to look at that I haven't posted here, the github repository for this project is here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蛮可爱 2024-12-07 17:20:23

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

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

My django is getting rusty, but here goes:

posts = Post.objects.filter(user__following__user=request.user)
夢归不見 2024-12-07 17:20:23
from django.db import transaction

@transaction.commit_manually
def get_posts(following):
    posts = []
    for f in following:
        posts.append(Post.objects.filter(user=f))
    transaction.commit()
    return posts

def home(request):
    following = Following.objects.filter(user=request.user)
    posts = get_posts(following)
from django.db import transaction

@transaction.commit_manually
def get_posts(following):
    posts = []
    for f in following:
        posts.append(Post.objects.filter(user=f))
    transaction.commit()
    return posts

def home(request):
    following = Following.objects.filter(user=request.user)
    posts = get_posts(following)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文