作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我目前正在使用 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
其中 123
是 my_profile
的 id
。
如果一个人多次关注另一个人(这里可能会发生这种情况,因为您没有强制 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/
我是一名优秀的程序员,十分优秀!