Phil Gyford
Phil Gyford

Reputation: 14654

Wagtail: Filter Pages by a ForeignKey

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?

Upvotes: 0

Views: 719

Answers (1)

gasman
gasman

Reputation: 25292

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)

Upvotes: 5

Related Questions