Serve user-wise data beautifully, minimally and correctly.
For a lot of web applications - Blogs come to mind as a canonical example, the queryset needs to be filtered in the views based upon some business rules. For instance, in a Blog, a “Dashboard” view - allowing editing of posts, should only ever have posts written by the user who is currently logged-in.
In general, there is a need to filter data based on some business logic - universally! i.e. across each and every view. The ugly way of doing this would be to write queries substantiating the business logic in every single view. Sieve does the same job beautifully, minimally and correctly.
We are at the cheeseshop:
pip install django_sieve
To use django_sieve in a project:
Include it in INSTALLED\_APPS
in your settings file.
Define a sieve model. A sieve model is the control for defining the filtering criteria of user data. For instance, in our example, we have a bookstore in which a user can subscribe to all the books from a particular author or all the books from a few publishers. In this case, his book list need to only contain books from the author and publishers that he has chosen. In order to do this, we define a sieve model like so:
class Sieve(models.Model):
group = models.ForeignKey('auth.Group')
publisher = models.ManyToManyField(Publisher)
author = models.ForeignKey(Author)
SIEVE_MODEL = 'bookstore.Sieve'
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
objects = SieveManager()
class BookView(ListView):
queryset = Book.objects.sieve(user=request.user)
That is all. Site-wide filtering of user data based on predefined criteria without having to write queries for all the views.
Please be wary of performance issues though - in our experience, django-sieve works for 90% cases especially when you need to bring everything up for a quick demo. However, as your site matures and the number of users increase, you may want to invest in profiling your views and hand-crafting these queries when and where required.