简体   繁体   中英

Filtering a request based on query parameters not present in model

We have an endpoint that lets you search for events between two dates.

/events?start_time=X&end_time=X

Events are a model with:

  • id
  • name
  • event_date

Should we be doing validation on the start_time and end_time parameters in the View, Serializer, or Model?

We want to make sure the start_time parameter is included, end_time is optional, and ensure that both are well formatted dates.

Is this custom logic in the view or is there a set of helpers that DRF (or Django) provides to perform this validation?

This is filtering , so it should be done on the queryset in the view. Validation of that data should also be done there I guess. You may use a dedicated serializer to validate that data (in get_queryset for example).

However, I would suggest using django-filter which will take care if the validation for you.

Maybe a filterset like this:

from django_filters import rest_framework as filters

class EventFilterset(filters.FilterSet)
    start_time=filters.DateFilter(name='event_date', lookup_expr='gte')
    end_time=filters.DateFilter(name='event_date', lookup_expr='lte')

    class Meta:
        model=Events
        fields=['start_time', 'end_time']

I'm not sure if you need the class Meta part.

Full documentation here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM