gpt4 book ai didi

python - 如何过滤 Django 子外键字段?

转载 作者:太空宇宙 更新时间:2023-11-03 15:53:16 24 4
gpt4 key购买 nike

所以我有以下模型:

建议文章:

linked_article = models.ForeignKey('Article', blank=True, null=True, db_constraint=False)
... more fields which aren't relevant to this question ...

文章:

title=models.CharField(max_length=60)
draft_state=models.BooleanField(default=True)
... More fields which aren't relevant to this questions ...

在文章模型中,有一个字段 draft_state,它允许我将文章的状态更改为已发布、草稿、已阻止(1、2、3)。

我正在获取所有 SuggestedArticle,并且想要过滤外键文章以确保存在 draft_state === 1。这是我目前拥有的一些伪代码,我认为实现此目的的代码可能如下所示:

 suggested_article = SuggestedArticle.objects\
.filter(
is_active=1,
Article.draft_state=1, # Something like this?! <~~~~~
state__in=[state, 'ALL'],
)\

我可以用 django 做到这一点吗?

最佳答案

Django offers a powerful and intuitive way to “follow” relationships in lookups, taking care of the SQL JOINs for you automatically, behind the scenes. To span a relationship, just use the field name of related fields across models, separated by double underscores, until you get to the field you want:

suggested_article = SuggestedArticle.objects.filter(
is_active=1,
state__in=[state, 'ALL'],
linked_article__draft_state=True
)

关于python - 如何过滤 Django 子外键字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41052856/

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