A predicate class constructed like Django Q objects, used to test whether a new or modified model would match a query
Project description
django-predicate provides a Q like object to facilitate the question: “would this model instance be part of a query” but without running the query or even saving the object.
Quickstart
Install django-predicate:
pip install django-predicate
Then use the P object just as you would Q objects:
from predicate import P
p = P(some_field__startswith="hello", age__gt=20)
You can then call the eval method with a model instance to check whether it passes the conditions:
model_instance = MyModel(some_field="hello there", age=21)
other_model_instance = MyModel(some_field="hello there", age=10)
p.eval(model_instance)
>>> True
p.eval(other_model_instance)
>>> False
or you can use Python’s in operator.
model_instance in p
>>> True
Even though a predicate is not a true container class - it can be used as (and was designed as being) a virtual “set” of objects that meets some condiiton.
Like Q objects, P objects can be &’ed and |’ed together to form more complex logic groupings.
In fact, P objects are actually a subclass of Q objects, so you can use them in queryset filter statements:
qs = MyModel.objects.filter(p)
If you have a situation where you want to use querysets and predicates based on the same conditions, it is far better to start with the predicate. Because of the way querysets assume a SQL context, it is non-trivial to reverse engineer them back into a predicate. However as seen above, it is very straightforward to create a queryset based on a predicate.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
File details
Details for the file django-predicate-1.0.0.tar.gz
.
File metadata
- Download URL: django-predicate-1.0.0.tar.gz
- Upload date:
- Size: 6.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 60a39f6ab110e41edbf4b6e4da28ab4a99afafbe99875e3afc463b110e3ebaa3 |
|
MD5 | 8ca0f3204b27cb8c43d6b78fee560324 |
|
BLAKE2b-256 | f35905d2c5d28a19d0bf36970b19c50e7e4c36261f5d7b70089a7074663397bc |