Skip to main content

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

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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-predicate-0.1.tar.gz (12.0 kB view details)

Uploaded Source

File details

Details for the file django-predicate-0.1.tar.gz.

File metadata

File hashes

Hashes for django-predicate-0.1.tar.gz
Algorithm Hash digest
SHA256 07783f738effc9d2cb44f8ec26e351074e1025338f95c3261b2def961795a51d
MD5 cda4d67441836f18ac7607f2918d66cd
BLAKE2b-256 10df713fcf92cd6aa0b1da2719263bd4d2cdb105bd86261a4180d58da6e6f435

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page