Wagtail: Filter Pages by a ForeignKey

早过忘川 提交于 2021-01-29 09:20:58

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!