g:通过ForeignKey过滤页面 [英] Wagtail: Filter Pages by a ForeignKey
问题描述
使用 Wagtail 我想获取一个 Page
的查询集,其特定子类具有一个 Snippet
的某些ForeignKey.
Using Wagtail I want to get a QuerySet of Page
s whose specific subclass have a certain ForeignKey to a Snippet
.
from django.db import models
from wagtail.core.models import Page
from wagtail.snippets.models import register_snippet
@register_snippet
class Organization(models.Model):
name = models.CharField(max_length=255, blank=False)
class ArticlePage(Page):
organization = models.ForeignKey(
'Organization',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+'
)
因此,我如何获取所有 Page
的查询集,这些查询集的关联 ArticlePage
具有带有 id的
Organization
1
的code>?
So, how would I get a QuerySet of all Page
s whose associated ArticlePage
has an Organisation
with an id
of 1
?
推荐答案
ArticlePage.objects.filter(organisation__id=1)
这将为您提供 ArticlePage
对象的查询集,通常比 Page
对象的查询集更可取,因为它还将为您提供Page的所有功能以及ArticlePage上定义的任何其他字段和方法.如果出于某种原因您需要它们成为基本的 Page
对象,则可以使用:
This will give you a queryset of ArticlePage
objects, which is usually preferable to a queryset of Page
objects as it will give you all of the functionality of Page as well as any additional fields and methods defined on ArticlePage. If for some reason you need them to be basic Page
objects, you can use:
Page.objects.filter(articlepage__organisation__id=1)
这篇关于g:通过ForeignKey过滤页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!