问题
Using Wagtail I want to get a QuerySet of Pages 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='+'
)
So, how would I get a QuerySet of all Pages whose associated ArticlePage has an Organisation with an id of 1?
回答1:
ArticlePage.objects.filter(organisation__id=1)
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)
来源:https://stackoverflow.com/questions/53394289/wagtail-filter-pages-by-a-foreignkey