Skip to main content

Decorator for Django model properties that checks if an annotation exists on the instance.

Project description

Django Annotated Property

Decorator for Django model properties that returns annotated values when available, avoiding database queries (f.e. O(N) vs O(1) for N items).

If a queryset includes annotated_<property>, the decorator uses it instead of calling the original method.

Example

from django.db import models
from django_annotated_property.annotated_property import annotated_property

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=8, decimal_places=2)

class OrderItem(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField()

    @annotated_property
    def total_price(self):
        return self.product.price * self.quantity

now you can use the total_price property in your views or templates:

items = (
    OrderItem.objects
    .annotate(annotated_total_price=models.F('product__price') * models.F('quantity'))
)
for item in items:
    print(item.total_price)  # returns annotated_total_price instead of the original method

TODO

  • Add tests

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_annotated_property-0.1.0.tar.gz (3.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_annotated_property-0.1.0-py3-none-any.whl (3.7 kB view details)

Uploaded Python 3

File details

Details for the file django_annotated_property-0.1.0.tar.gz.

File metadata

File hashes

Hashes for django_annotated_property-0.1.0.tar.gz
Algorithm Hash digest
SHA256 a3f1536b431de0ec16c80b405d2452ffbf00cd230317e465d85998e26af9c3ed
MD5 3ee17cf38ae3e0b8fd24006a05d02ba7
BLAKE2b-256 2a53e52b3a851bd8ef742d3662fd224760918c6b701e927a9958c9c851a488be

See more details on using hashes here.

File details

Details for the file django_annotated_property-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for django_annotated_property-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 fad359e48665bd5a41c61d6c26fd9da8713260fbc2e731bb4cc1fd5e83e6d4cb
MD5 a3052c90ce4a1f0bf65eb2b92d1481e1
BLAKE2b-256 bda754696c2cd83b35e7805d818cd0082647226bda5665824f183f335472cda2

See more details on using hashes here.

Supported by

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