Mark P
Mark P

Reputation: 31

Is it possible to filter by the 'year' of a 'date field' while using the Wagtail v2 API and search_fields in the model

What we are building

We are building a Wagtail 4.2.4 implementation that allows an admin user to add content through the GUI. One field in the model of that content type (or app) is a date field which uses a datepicker to select the published date field in the GUI.

All the content associated with the content type (very similar to the default blog example from wagtail) is then served via an API for the front end to consume.

One of the front-end requirements is to filter by year , to make this easier for the dev I would like to make the API call itself filterable by year.

What I have tried

I have scoured all documentation and approaches and have come to nought. Ideally, we need a similar queryset result method to models.blog.objects.all().filter(date__year=year) but instead a index.FilterField('date_year'), type approach inside search_fields .

Below is the simplified model from models.py which shows how the date field is currently implemented along with search_field and api_fields.

Note that adding a serialized date field date_year by changing the formating didn't work.

Model

class BlogPage(Page):

    date = models.DateField("Post date")

    content_panels = Page.content_panels + [
        ...
        FieldPanel('date'),
        ...
    ]

    search_fields = Page.search_fields + [
        ...
        index.FilterField('date'),
        ...
    ]

    api_fields = [
        ...
        APIField('date'),
        APIField('date_year', serializer=DateField(format='%Y', source='date')),
        ...
    ]

Upvotes: 0

Views: 51

Answers (0)

Related Questions