如何查询 Django 多对多关系,它有一个中间模型来处理关系?

问题描述 投票:0回答:0

这可能是一个非常简单的问题,但到目前为止我还没有弄清楚。

我在 Django 模型中有这样的多对多关系:

class Post(models.Model):
    ...

class PostCategory(models.Model):
    ...

class PostPagePostCategory(models.Model):
    """A connection class needed for other things to work.
    It is not possible to sily have the ParentalManyToMany field."""
    post = ParentalKey(
        'models.PostPage',
        on_delete=models.CASCADE,
        related_name='post_categories',
    )
    post_category = models.ForeignKey(
        'models.PostCategory',
        on_delete=models.CASCADE,
        related_name='posts',
    )

    class Meta:
        unique_together = ('post_page', 'post_category')

如类文档字符串中所述,由于其他要求,我不能简单地使用 ParentalManyToMany 字段。

现在我的问题是如何执行以下查询。 假设我选择了一些帖子,例如

posts = Post.objects.filter(...)
,我只想为这些帖子选择所有类别。如何执行这样的查询?

如果我查询

categories = PostCategory.objects.filter(post__in=posts)
,我得到以下错误:
ValueError: Cannot query 'posts': Must be "PostPagePostCategory" instance.

如果我查询

PostPagePostCategory.objects.filter(post__in=posts)
,我显然会得到
PostPagePostCategory
带有
PostPagePostCategory
的查询集。

我现在如何从

PostPagePostCategory
查询集中获得不同的
PostCategory
对象?

django django-models django-queryset
© www.soinside.com 2019 - 2024. All rights reserved.