在Django中使用像SQLAlchemy这样的“join-query”?

时间:2017-10-04 04:21:24

标签: django

如何在Django中使用:获取用户follow_set所有文章?

在sqlAlchemy中使用:

Article.query.join(Follow, Follow.followed_id == Article.user_id)\
                .filter(Follow.follower_id == self.id)

我的代码:

class User(AbstractUser):  # Author
    pass

class Article(models.Model):
    content = models.TextField()
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

class Follow(models.Model):  # user ManyToMany
    timestamp = models.DateField(auto_now_add=True)
    follower = models.ForeignKey(User, related_name='followed_set', on_delete=models.CASCADE)
    followed = models.ForeignKey(User, related_name='follower_set', on_delete=models.CASCADE)

1 个答案:

答案 0 :(得分:0)

一种方法可以获得用户的所有跟踪。

followed =  Follow.objects.filter(followed=user).values('followed')
articles = Article.objects.filter(user__in=followed)