Django DRF - Where to enforce data consistency constraints

Hi,

I’ve been developing an application that makes use of the DRF. I have lots of conditions regarding data, for example a model called ‘Instrument’ with a status field (active, inactive) which has a foreign key to a ‘Tag’. Many instruments may reference one tag, but only one of those instruments per tag may have a status of ‘Active’ at any given time.

Currently any sort of conditions like this I handle in my ModelViewSets in the create/update functions etc, but this obviously does not apply the logic to any modifications performed outside of the DRF (i.e. django admin panel).

What is the accepted practice for enforcing these types of constraints on data?

Thanks!

Take a look at Django Model Constraints.

Also see Constraints reference | Django documentation | Django

And the set of blog posts by @adamchainz where he shows different examples of creating and using constraints:

Using Django Check Constraints to Ensure Only One Field Is Set - Adam Johnson
Using Django Check Constraints to Limit the Range of an IntegerField - Adam…
Using Django Check Constraints to Prevent Self-Following - Adam Johnson]

(There are a couple more, but these should give you some good ideas.)

Awesome, those articles look great. Thank you!