# -*- coding: utf-8 -*-
from setuptools import setup

package_dir = \
{'': 'src'}

packages = \
['django_shared_property']

package_data = \
{'': ['*']}

setup_kwargs = {
    'name': 'django-shared-property',
    'version': '0.5.3',
    'description': 'Properties that are both ORM expressions and python code.',
    'long_description': '======================\nDjango Shared Property\n======================\n\n\n.. image:: https://img.shields.io/pypi/v/django_shared_property.svg\n        :target: https://pypi.python.org/pypi/django_shared_property\n\n.. image:: https://img.shields.io/travis/schinckel/django-shared-property.svg\n        :target: https://travis-ci.org/schinckel/django-shared-property\n\n.. image:: https://ci.appveyor.com/api/projects/status/schinckel/branch/main?svg=true\n    :target: https://ci.appveyor.com/project/schinckel/django-shared-property/branch/main\n    :alt: Build status on Appveyor\n\n.. image:: https://readthedocs.org/projects/django-shared-property/badge/?version=latest\n        :target: https://django-shared-property.readthedocs.io/en/latest/?badge=latest\n        :alt: Documentation Status\n\n\n\n\nProperties that are both ORM expressions and python code.\n\n\n* Free software: MIT license\n\n* Documentation: https://django-shared-property.readthedocs.io.\n\n\n\nInstallation:\n-------------\n\n.. code-block:: console\n\n    $ pip install django_shared_property\n\nPhilosophy:\n-------------\n\nI often find that I have annotations in Django querysets that are based on one or more other fields, and are used frequently. In some cases I have even been known to ensure these annotations are always available on the model using a custom queryset/manager.\n\nBut, unlike Python properties, these annotations are not "live". If, for example, you have the following:\n\n.. code-block:: python\n\n    class FullNameQueryset(models.query.QuerySet):\n        def with_full_name(self):\n            return self.annotate(\n              full_name=Concat(models.F(\'first_name\'), models.Value(\' \'), models.F(\'last_name\')),\n            )\n\n\n    class Person(models.Model):\n        first_name = models.TextField()\n        last_name = models.TextField()\n\n        objects = FullNameQueryset.as_manager()\n\n\nThen, you can do a `person = Person.objects.with_full_name().get(pk=1)`, and then reference `person.full_name`.\n\nBut, if you modify `person.first_name`, you\'d need to write it back to the database, and then reload it. Which may not be ideal, and at best requires two database operations.\n\ndjango-shared-property allows you to have properties that automatically act as an annototation, allowing you to define the expression, and have Django use that operation within any database query. It can then be used in a filter (or further annotation), even across relationships. And finally, if any local changes are made to the object that would affect the value when stored in the database, then the property value will also update in Python.\n\nShow me how!\n-------------\n\nSimilar to a Python property, a django-shared-property requires a method that takes no arguments. It should, however, return a Django Expression. For example, following our annotation above:\n\n.. code-block:: python\n\n    class Person(models.Model):\n        first_name = models.TextField()\n        last_name = models.TextField()\n\n        @shared_property\n        def full_name(self):\n            return Concat(models.F(\'first_name\'), models.Value(\' \'), models.F(\'last_name\'))\n\n\nYou then reference it just like any other field.\n\n.. code-block:: python\n\n\n    Person.objects.filter(full_name__contains=\'Bob\')\n\n\nWhat else can it do?\n---------------------\n\nShared properties can reference any number of fields on the model, and even other shared properties, just like with annotations. They can even reference fields from related models, using the familiar ``models.F(\'relation__field\')`` lookup syntax. You can also use some Django expressions (such as Concat, Lower, Upper), where there is a clear relationship to a Python concept.\n\n  * Case\n  * When\n  * F\n  * Q (Specifically, within a When, but it could work elsewhere)\n  * Concat\n  * Value\n  * Lower and Upper (but only on Python objects that have these as attributes)\n  * ExpressionWrapper\n  * CombinedExpresson\n  * Coalesce (but see the note below)\n\nWithin the context of a Q expression, you can use ``__isnull`` and ``__exact`` lookups.\n\n\nYou can even refer to constants in your Python file, such as the different values of an Enum. The return value of your python object will then correctly return instances of the Enum.\n\n\nIf your chosen expression/function/value does not work, then it may be possible to implement it (see below).\n\n\nShared properties should be pure functions - they must not refer to ``self`` (indeed, this will cause an error), and should not refer to variables, as they will be executed at times other than when they are about to be decorated.\n\n\nHow does it work?\n------------------\n\nBecause of the limit that the decorated function be a pure function, we are able to execute the callable, using the result as a Django expression.\n\nThe Django part is relatively straightforward. The expression returned by the method that is decorated as a shared_property is used in a context that looks a bit like an annotation - however there are a couple of things that need to be done to ensure that the expression has the correct data available to it to make sure it points at the correct tables. We indicate to Django  that it should not be written back to the database by marking it as a ``private`` field.\n\nCreating the Python property is a bit trickier. We still need the expression, but we build an Abstract Syntax Tree based on the expression. We then compile this into a callable object that we use as the property.\n\nIn a little more detail:\n\n  * Call the decorated function, returning the Expression\n  * Use Python\'s introspection tools to examine the expression (and it\'s "source expressions") and a recursive descent parser to build an AST equivalent to the expression. Specifically, the AST contains a function definition.\n  * Compile this AST into a code object\n  * ``eval`` this code object with the correct context to pull in any constants from outside the namespace.\n  * Extract the newly defined function, and use it for the callable in our property.\n\n\nAdvanced Use\n-------------\n\nSometimes you want to define the callable yourself: there is an alternate syntax for that. This could be where the expression has not been defined, or it\'s possible to create a more efficient callable by hand:\n\n.. code-block:: python\n\n    class MyModel(models.Model):\n        # other fields\n\n        @shared_property(Case(\n            When(models.Q(x__gte=2, x__lt=5), then=models.Value(\'B\')),\n            When(models.Q(x__lt=2), then=models.Value(\'A\')),\n            default=models.Value(\'C\'),\n            output_field=models.TextField(),\n        )\n        def state(self):\n            if 2 <= self.x < 5:\n                return \'B\'\n            elif x < 2:\n                return \'A\'\n            return \'C\'\n\n        @shared_property(Coalesce(\n          CombinedExpression(F(\'expiry_date\'), \'<\', Func(function=\'current_timestamp\')),\n          models.Value(True),\n        ))\n        def active(self):\n            return self.expiry_date is None or self.expiry_date < timezone.now()\n\n\nIn this specific case, the code that is generated would be fairly similar (although it would not use the ``a < b < c`` idiom), however it shows how it is possible to to explicitly provide the python code. Please note that the onus of responsibility is on the developer to ensure that the expression and function are equivalent in this context.\n\nThe second example shows where a python comparison doesn\'t quite map to the SQL code: the ``COALESCE(expiry_date < now(), true)`` relies on SQL comparisons involving NULL to also return NULL, but in Python you cannot do this.\n\nAlso note that in this case only a single expression may be used as the argument to the decorator.\n\nRegistering Expressions\n-----------------------\n\nIt is possible to register your own expressions. The structure is quite strict, and you\'ll need to reference the parser instance as well as the incoming expression. There\'s sometimes quite a bit of work to turn the Expression into (a) the correct Python, and then (b) the AST that is required.\n\n\n.. code-block:: python\n\n    from django_shared_property.parser import register\n\n\n    @register\n    def handle_foo(parser, expression):\n        # This assumes a foo() function in python that matches a foo()\n        # function in SQL, neither of which takes arguments.\n        return Call(\n            func=Name(id=\'foo\', **parser.file),\n            args=[],\n            keywords=[],\n            kwonlyargs=[],\n            **parser.file,\n        )\n\n\n    class Foo(Func):\n        function = \'foo\'\n\n\n    class MyModel(models.Model):\n        # ...\n\n        @shared_property\n        def the_foo(self):\n            return Foo()\n\n\nThis is a toy example - try looking in the ``parser`` module for other examples.\n\nLimitations\n-----------\n\nUse of the django queryset methods defer/only prevent any shared properties from loading. However, because of the way the feature works, you would still be able to use this property - at least in the case where the referenced fields are local.\n\nWhen you use a shared property that references a related model, and then try to filter on this, you cannot perform a count or exists query. See https://github.com/schinckel/django-shared-property/issues/2\n\n\nCredits\n-------\n\nDeveloped by `Matthew Schinckel`_.\n\nThis package was created with Cookiecutter_ and the `wboxx1/cookiecutter-pypackage-poetry`_ project template.\n\n.. _`Matthew Schinckel`: https://schinckel.net/\n.. _Cookiecutter: https://github.com/audreyr/cookiecutter\n.. _`wboxx1/cookiecutter-pypackage-poetry`: https://github.com/wboxx1/cookiecutter-pypackage-poetry\n',
    'author': 'Matthew Schinckel',
    'author_email': 'matt@schinckel.net',
    'maintainer': None,
    'maintainer_email': None,
    'url': 'https://django-shared-property.readthedocs.io',
    'package_dir': package_dir,
    'packages': packages,
    'package_data': package_data,
    'python_requires': '>3.8',
}


setup(**setup_kwargs)
