Traits for Django
Project description
django-traits
Define traits for Django models that works seamlessly both in-Python and using the ORM, with coordinated tests.
Installation
$ python3 -m pip install django-traits
Example
class Rich(Trait["Person"]):
q = models.Q(income__gt=1000)
def check_instance(self, instance: Person) -> bool:
return instance.income > 1000
class Person(models.Model):
is_rich = Rich()
income = models.PositiveIntegerField()
# Filter for rich people, this uses the ORM predicate as defined in q.
rich_people = Person.is_rich.all()
# Check if a person is rich, this uses the in-Python predicate as defined in check_instance().
person = Person.objects.first()
if person.is_rich:
print("Money is not a problem")
else:
print("This person is not rich")
The automated test factory makes it simple to write tests that guarantees that the in-Python predicate stays in sync with its ORM counterpart.
class TestPerson:
test_is_rich = test_trait(
(
(PersonFactory(), False),
(PersonFactory(income=1000), False),
(PersonFactory(income=1001), True),
)
)
The above example will generate tests that exercises the in-Python predicate on
instances of Person
, as well as tests that tries to filter using the ORM predicate.
That means that if the implementations were to drift apart, for instance if the limit
was increased to 2000
in check_instance()
but not in q
, the tests would fail.
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
Built Distribution
File details
Details for the file django-traits-0.0.1.tar.gz
.
File metadata
- Download URL: django-traits-0.0.1.tar.gz
- Upload date:
- Size: 4.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 7f6a1c3e7d84f7923218c895aa8480928aca910da1675e1a2dc50a8131b8aeb2 |
|
MD5 | d9d61d45d15fb5a4ae0a90649e71abe0 |
|
BLAKE2b-256 | 28c72ec46613a03e18286aa26dc2a3ab9384ecf9a5d9f2a5aa9d645117bd756c |
File details
Details for the file django_traits-0.0.1-py3-none-any.whl
.
File metadata
- Download URL: django_traits-0.0.1-py3-none-any.whl
- Upload date:
- Size: 4.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 484fb5d49c2645c5ecd1896889d4cd3d2c5c203d1d3e1b0fd588fc5972ba091f |
|
MD5 | 1f52481835f2d9af915a24f5a2d67bb8 |
|
BLAKE2b-256 | 69c32b925bf87fe8ec5631e093d5322236606449bdb706d65e1b29da8b5e6a02 |