根据另一个模型的字段过滤一个模型

Filtering one model based on another model's field

我有以下型号:

class User(AbstractUser):
    pass

class Post(models.Model):
    post_user = models.ForeignKey(User, on_delete=models.CASCADE)
    post_content = models.TextField()
    post_date = models.DateTimeField(default=timezone.now)

class Follow(models.Model):
    follow_user = models.ForeignKey(User, on_delete=models.CASCADE)
    follow_target = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follow_target')

我正在尝试为我关注的用户(我是当前登录的用户)创建的所有帖子创建一个查询集。我的查询集目前看起来像这样,但我不断收到 NameError: field not found:

postresult = Post.objects.all().filter(post_user=follow__follow_target, follow__follow_user=request.user)

任何帮助将不胜感激!

您过滤:

postresult = Post.objects.filter(
    <b>post_user__follow_target__follow_user=request.user</b>
)

post_user 将跟随 ForeignKeyPostUser。然后我们使用 related_name='follow_target' 来跟踪到 Follow 对象的关系,然后我们使用 follow_user 来检索以下用户。


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.


Note: The related_name=… parameter [Django-doc] is the name of the relation in reverse, so from the User model to the Follow model in this case. Therefore it (often) makes not much sense to name it the same as the forward relation. You thus might want to consider renaming the follow_target relation to followers.

如果您重命名相关名称,则查询为:

postresult = Post.objects.filter(
    <b>post_user__followers__follow_user=request.user</b>
)