-
-
Save isaku-dev/8d146ec2380dec59fb012cf576186c3c to your computer and use it in GitHub Desktop.
Django: Reusable model filtering: Using QuerySet.as_manager() properly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # http://www.dabapps.com/blog/higher-level-query-api-django-orm/ | |
| # Converted to use Django 1.8 QuerySet.as_manager() | |
| # We inherit custom QuerySet to define new methods | |
| class TodoQuerySet(models.query.QuerySet): | |
| def incomplete(self): | |
| return self.filter(is_done=False) | |
| def high_priority(self): | |
| return self.filter(priority=1) | |
| class Todo(models.Model): | |
| content = models.CharField(max_length=100) | |
| # other fields go here.. | |
| objects = TodoQuerySet.as_manager() # Activate custom QuerySet |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Now that we have a custom manager on Todo, we can chain filters | |
| # e.g. | |
| all = Todo.objects.all() | |
| incomplete = Todo.objects.incomplete() | |
| incomplete_hp = Todo.objects.incomplete().high_priority() | |
| # This is super useful because it allows removing .filter(XXXXXXX) | |
| # from View and improves maintainability in complex projects a lot. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment