gpt4 book ai didi

Django查询: How to find all posts from people you follow

转载 作者:行者123 更新时间:2023-12-02 06:57:35 25 4
gpt4 key购买 nike

我目前正在使用 Django 框架构建一个网站。我希望在我的网站的主页上显示用户关注的人发布的所有帖子。以下是个人资料、故事和关注的类:

class Profile(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
first_name = models.CharField(max_length=30, null=True)
last_name = models.CharField(max_length=30, null=True)

class Follow(models.Model):
following = models.ForeignKey('Profile', on_delete=models.CASCADE, related_name="following")
follower = models.ForeignKey('Profile', on_delete=models.CASCADE, related_name="follower")
follow_time = models.DateTimeField(auto_now=True)

class Story(models.Model):
author = models.ForeignKey('accounts.Profile', on_delete=models.CASCADE, related_name="author")
title = models.CharField(max_length=50)
content = models.TextField(max_length=10000)

如您所见,Follow 使用两个外键来表示关注者和关注者。有没有办法查询用户关注的人的所有故事?

我真的不知道要过滤什么。或者这可能是聚合的工作?如果有人可以帮助我,那就太好了!

following_feed = Story.object.filter(???).order_by('-creation_date')

最佳答案

可以使用下划线(__)来“查看”关系(例如ForeignKey等)。

所以在这里我们可以过滤:

Story.objects.filter(
<b>author__following__follower=my_profile</b>
)

因此,通过使用 author 我们获得对作者的 Profile 的引用,然后使用 following 我们查看 Follow 模型,最后通过 follower 我们再次获得对 Profile 的引用:follower 的个人资料。

my_profile 当然需要替换为 Profile 对象(follower 的个人资料)您想要获取的故事的作者)。

这将生成如下查询:

SELECT s.*
FROM story AS s
JOIN follow AS f ON f.following_id = s.author_id
WHERE f.follower_id = 123

其中 123my_profileid

如果一个人多次关注另一个人(这里可能会发生这种情况,因为您没有强制 follower、following 元组在 Follow 模型中是唯一的),那么相应的Story将会产生多次次。

因此,最好在 Follow 模型中添加 unique_together 约束:

class Follow(models.Model):
following = models.ForeignKey(
'Profile',
on_delete=models.CASCADE,
related_name="following"
)
follower = models.ForeignKey(
'Profile',
on_delete=models.CASCADE,
related_name="follower"
)
follow_time = models.DateTimeField(auto_now=True)

class Meta:
<b>unique_together</b> = (<b>('following', 'follower')</b>, )

也可能值得将 Follow 模型视为 ManyToManyField [Django-doc]through 模型。 .

关于Django查询: How to find all posts from people you follow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53803106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com