I have a strange need, a customer asked me to implement a webapp to support his database. Since I love Django I decided to use it.
The extra need which I have difficult with is as follow: the user should have the extra “power” to create model constraints like checking the range of an IntegerField, all without knowing anything about Python.
So, I have some ideas but I’m not sure what is (if there is) the correct one. Here’s my thoughts:
- Implement a template-side validation using JavaScript
- Implement a Python Script and a userfriendly way to use it that writes the models.py file (this sounds terrible)
- Write some Admin Actions using a raw SQL CHECK constraint, but I still don’t know how
Is this request solvable? Can you give me a tip about the simplest way to do it?
Thanks in advance,
—
Flavio
Yes, it is possible indeed. We will use custom object manager and dynamic Q objects to solve the issue. Here’s an example.
Create an appropriate model to store info about constraints. Note that we create ForeginKey to
ContentTypein order to tie our constraint to a specific model class.Create a custom manager, register it with your models.
So in your views you will be able to use it like this:
YourModel.c.get_constrainted_query(user)Note that I didn’t test this code, but I hope you’ve grasped the concept.
To override queries inside ModelAdmin, use this and this techniques.