Limit related data choices with Django REST framework

Xavier Ordoquy
Django REST framework
1 min readMar 16, 2016

One question I’ve seen on a regular basis is “With Django REST framework, how do I restrict my related data choices according to some criteria” ?

Django REST framework 3.3.3 introduces an option to deal with that use case, thanks to Ryan Hiebert for the pull request (#3605).

Let’s start with two basic models:

Let’s create a few Attribute instances:

  • attr1, attr3 assigned to the admin user
  • attr2, attr4 assigned to another user.

With the most basic serializer for Invoice we’ll get the four attributes as possible choices for the invoice instance.

You may define an explicit field for the attributes and play with the queryset to restrict the set to active attributes for example but nothing dynamic.

What if we want to restrict the attributes to the current user’s attribute ? Say if I’m logged as admin, I only want attr1 and attr3 as possible choices.

The way to deal with it is to override the get_queryset on the related field and explicitely define it within the serializer.

In that example, AttrPKField override the get_queryet which gets the current user and use it to filter the attributes against.

With that change, only attr1 and attr3 — which are linked to the current user — will appear.

Enjoy the new feature !

Want to see some Django REST framework topic covered ? let me know.

--

--

Xavier Ordoquy
Django REST framework

Django and Python coach, Freelance since 2004, part time developer, architect and admin.