pax_global_header00006660000000000000000000000064146657757110014535gustar00rootroot0000000000000052 comment=aeef1088a1c6d2be9f8ea90fd9f53a64be292ec3 jazzband-django-model-utils-aeef108/000077500000000000000000000000001466577571100175275ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/.coveragerc000066400000000000000000000001661466577571100216530ustar00rootroot00000000000000[run] include = model_utils/*.py [report] exclude_also = # Exclusive to mypy: if TYPE_CHECKING:$ \.\.\.$ jazzband-django-model-utils-aeef108/.editorconfig000066400000000000000000000003571466577571100222110ustar00rootroot00000000000000# https://editorconfig.org root = true [*] charset = utf-8 end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true [*.{py,rst,ini}] indent_style = space indent_size = 4 [*.yml] indent_style = space indent_size = 2 jazzband-django-model-utils-aeef108/.github/000077500000000000000000000000001466577571100210675ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/.github/ISSUE_TEMPLATE.md000066400000000000000000000004521466577571100235750ustar00rootroot00000000000000## Problem Explain the problem you encountered. ## Environment - Django Model Utils version: - Django version: - Python version: - Other libraries used, if any: ## Code examples Give code example that demonstrates the issue, or even better, write new tests that fails because of that issue. jazzband-django-model-utils-aeef108/.github/PULL_REQUEST_TEMPLATE.md000066400000000000000000000007551466577571100246770ustar00rootroot00000000000000## Problem Explain the problem you are fixing (add the link to the related issue(s), if any). ## Solution Explain the solution that has been implemented, and what has been changed. ## Commandments - [ ] Write PEP8 compliant code. - [ ] Cover it with tests. - [ ] Update `CHANGES.rst` file to describe the changes, and quote according issue with `GH-`. - [ ] Pay attention to backward compatibility, or if it breaks it, explain why. - [ ] Update documentation (if relevant). jazzband-django-model-utils-aeef108/.github/workflows/000077500000000000000000000000001466577571100231245ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/.github/workflows/issue-manager.yml000066400000000000000000000027321466577571100264130ustar00rootroot00000000000000# Automatically close issues or pull requests that have a label, after a custom delay, if no one replies. # https://github.com/tiangolo/issue-manager name: Issue Manager on: schedule: - cron: "12 0 * * *" issue_comment: types: - created issues: types: - labeled pull_request_target: types: - labeled workflow_dispatch: jobs: issue-manager: # Disables this workflow from running in a repository that is not part of the indicated organization/user if: github.repository_owner == 'jazzband' runs-on: ubuntu-latest steps: - uses: tiangolo/issue-manager@0.5.0 with: token: ${{ secrets.GITHUB_TOKEN }} config: > { "answered": { "delay": 864000, "message": "Assuming the question was answered, this will be automatically closed now." }, "solved": { "delay": 864000, "message": "Assuming the original issue was solved, it will be automatically closed now." }, "waiting": { "delay": 864000, "message": "Automatically closing after waiting for additional info. To re-open, please provide the additional information requested." }, "wontfix": { "delay": 864000, "message": "As discussed, we won't be implementing this. Automatically closing." } } jazzband-django-model-utils-aeef108/.github/workflows/release.yml000066400000000000000000000017601466577571100252730ustar00rootroot00000000000000name: Release on: push: tags: - '*' jobs: build: if: github.repository == 'jazzband/django-model-utils' runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 with: fetch-depth: 0 - name: Set up Python uses: actions/setup-python@v4 with: python-version: 3.x - name: Install dependencies run: | python -m pip install -U pip python -m pip install -U setuptools twine wheel - name: Build package run: | python setup.py --version python setup.py sdist --format=gztar bdist_wheel twine check dist/* - name: Upload packages to Jazzband if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags') uses: pypa/gh-action-pypi-publish@master with: user: jazzband password: ${{ secrets.JAZZBAND_RELEASE_KEY }} repository_url: https://jazzband.co/projects/django-model-utils/upload jazzband-django-model-utils-aeef108/.github/workflows/test.yml000066400000000000000000000035571466577571100246400ustar00rootroot00000000000000name: Test on: [push, pull_request] env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: postgres FORCE_COLOR: 1 jobs: build: runs-on: ubuntu-latest strategy: fail-fast: false max-parallel: 5 matrix: python-version: ['3.8', '3.9', '3.10', '3.11', '3.12-dev'] services: postgres: image: postgres:13-alpine env: POSTGRES_USER: ${{ env.POSTGRES_USER }} POSTGRES_PASSWORD: ${{ env.POSTGRES_PASSWORD }} POSTGRES_DB: ${{ env.POSTGRES_DB }} ports: - 5432:5432 options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} - name: Get pip cache dir id: pip-cache run: | echo "::set-output name=dir::$(pip cache dir)" - name: Cache uses: actions/cache@v3 with: path: ${{ steps.pip-cache.outputs.dir }} key: ${{ matrix.python-version }}-v1-${{ hashFiles('**/setup.py') }}-${{ hashFiles('**/tox.ini') }} restore-keys: | ${{ matrix.python-version }}-v1- - name: Install dependencies run: | python -m pip install --upgrade pip python -m pip install --upgrade tox tox-gh-actions - name: Tox tests run: | tox -v -- --cov --cov-append --cov-report term-missing --cov-report xml env: POSTGRES_DB: ${{ env.POSTGRES_DB }} POSTGRES_USER: ${{ env.POSTGRES_USER }} POSTGRES_PASSWORD: ${{ env.POSTGRES_PASSWORD }} - name: Upload coverage uses: codecov/codecov-action@v3 with: name: Python ${{ matrix.python-version }} jazzband-django-model-utils-aeef108/.gitignore000066400000000000000000000002141466577571100215140ustar00rootroot00000000000000dist/* build django_model_utils.egg-info/* HGREV .coverage .tox/ Django-*.egg *.pyc htmlcov/ docs/_build/ .idea/ .eggs/ .venv/ coverage.xml jazzband-django-model-utils-aeef108/.pre-commit-config.yaml000066400000000000000000000007671466577571100240220ustar00rootroot00000000000000repos: - repo: https://github.com/PyCQA/isort rev: 5.13.2 hooks: - id: isort args: ['--profile', 'black', '--check-only', '--diff'] files: ^((model_utils|tests)/)|setup.py - repo: https://github.com/PyCQA/flake8 rev: 7.1.1 hooks: - id: flake8 args: ['--ignore=E402,E501,E731,W503'] files: ^(model_utils|tests)/ - repo: https://github.com/asottile/pyupgrade rev: v3.17.0 hooks: - id: pyupgrade args: [--py38-plus] jazzband-django-model-utils-aeef108/.readthedocs.yml000066400000000000000000000005171466577571100226200ustar00rootroot00000000000000# Read the Docs configuration file # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details # Project page: https://readthedocs.org/projects/django-model-utils/ version: 2 build: os: ubuntu-22.04 tools: python: "3" python: install: - method: pip path: . sphinx: configuration: docs/conf.py jazzband-django-model-utils-aeef108/AUTHORS.rst000066400000000000000000000101141466577571100214030ustar00rootroot00000000000000| Adam Bogdał | Adam Chainz | Adam Dobrawy | Adam Nelson | Alejandro Varas | Alex Orange | Alexander Kavanaugh | Alexey Evseev | Andy Freeland | Ant Somers | Antti Kaihola | Arseny Sysolyatin | Artis Avotins | Asif Saif Uddin | Bo Marchman | Bojan Mihelac | Bruno Alla | Bugra Aydin | Craig Anderson | Daniel Andrlik | Daniel Stanton | Den Lesnov | Diego Navarro | Dmytro Kyrychuck | Donald Stufft | Douglas Meehan | Emin Bugra Saral | Enrique Matías Sánchez | Eran Rundstein | Eugene Kuznetsov | Felipe Prenholato | Filipe Ximenes | Florian Alu | Germano Massullo | Gregor Müllegger | Guilherme Devincenzi | Guilherme Crocetti | Hanley | Hanley Hansen | Harry Moreno | Hasan Ramezani | Ivan Virabyan | JMP | Jack Cushman | James Oakley | Jannis Leidel | Javier Garcia Sogo | Jeff Elmore | Joe Riddle | John Vandenberg | Jonathan Sundqvist | João Amaro | Karl WnW | Keryn Knight | Lucas Wiman | Martey Dodoo | Matthew Schinckel | Matthieu Rigal | Michael van Tellingen | Mike Bryant | Mikhail Silonov | Misha Kalyna | Nick Sandford | Patryk Zawadzki | Paul McLanahan | Philipp Steinhardt | Radosław Ganczarek | Reece Dunham | Remy Suen | Rinat Shigapov | Rodney Folz | Romain G | Romain Garrigues | Roman | Ryan Kaskel | Ryan P Kilby | Ryan Senkbeil | Rémy HUBSCHER | Sachi King | Sebastian Illing | Sergey Tikhonov | Sergey Zherevchuk | Seán Hayes | Simon Charette | Simon Meers | Skia | Tavistock | Thomas Schreiber | Tony Aldridge | Tony Narlock | Travis Swicegood | Trey Hunner | Václav Dohnal | Zach Cheung | ad-m | asday | bboogaard | funkybob | georgemillard | jarekwg | romgar | silonov | smacker | zyegfryed | Éric Araujo | Őry Máté | Nafees Anwar | meanmail jazzband-django-model-utils-aeef108/CHANGES.rst000066400000000000000000000452451466577571100213430ustar00rootroot00000000000000Changelog ========= 5.0.0 (2024-09-01) ------------------ - Add formal support for `Django 5.1` - Remove MonitorField deprecation warning. `None` - instead of `django.utils.timezone.now` will be used when nullable and no default provided (GH-#599) - Add deprecation warning for MonitorField. The default value will be `None` instead of `django.utils.timezone.now` - when nullable and without a default. - Add Brazilian Portuguese translation (GH-#578) - Don't use `post_init` signal for initialize tracker - Make `contribute_to_class()` in `StatusField`, `MonitorField` and `SplitField` forward additional arguments to Django - `SplitField` no longer accepts `no_excerpt_field` as a keyword argument - Make `soft` argument to `SoftDeletableModel.delete()` keyword-only - `JoinManager` and `JoinManagerMixin` have been deprecated; please use ``JoinQueryset.as_manager()`` instead - Change `SoftDeletableQuerySetMixin.delete` to replicate Django's API. 4.5.1 (2024-05-02) ------------------ - Remove `JoinQueryset.get_quoted_query()` by @mthuurne (GH-#618) 4.5.0 (2024-04-01) ------------------ - Don't use `post_init` signal for initialize tracker by @meanmail in - (GH-#556) - clarify docs for managers of SoftDeletableModel by @tadamcz in - (GH-#589) - [pre-commit.ci] pre-commit autoupdate by @pre-commit-ci in - (GH-#575) - `Language Support` - Add translations for Brazilian Portuguese by @gmcrocetti in - (GH-#578) - Remove dead `init_deferred_fields` method by @joecox in - (GH-#580) - Update where `ConnectionDoesNotExist` is imported from by @mthuurne in - (GH-#566) - Remove arguments from `InheritanceQuerySetMixin._clone()` by @mthuurne in - (GH-#567) - Allow running tests using sqlite by @jayvdb in - (GH-#516) - `MonitorField` - Change default to None when the field is nullable by @gmcrocetti in - (GH-#577) - Explicitly re-export names from `__init__` module by @mthuurne in - (GH-#591) - Switch from freezegun to time-machine. by @adamchainz in - (GH-#510) - USE_TZ = True by @foarsitter in - (GH-#593) - Remove redundant definition of `JoinManager` from tests by @mthuurne in - (GH-#594) - Pass reason to `@skip` decorator by @mthuurne in - (GH-#595) - Resolve name clash among test models by @mthuurne in - (GH-#596) - Remove obsolete `tests.signals` module by @mthuurne in - (GH-#597) - Remove obsolete test models by @mthuurne in - (GH-#598) - Postgresql docker container for local development by @foarsitter in - (GH-#563) - [pre-commit.ci] pre-commit autoupdate by @pre-commit-ci in - (GH-#602) - Add issue-manager by @foarsitter in - (GH-#600) - Translation files by @foarsitter in - (GH-#608) 4.4.0 (2024-02-10) ------------------ - Add support for `Python 3.11` (GH-#545) - Add support for `Python 3.12` (GH-#545) - Drop support for `Python 3.7` (GH-#545) - Add support for `Django 4.2` - Add support for `Django 5.0` - Remove ``SaveSignalHandlingModel``. This model used a modified copy of the internal Django method `Model.save_base()` and had not been updated for upstream bug fixes changes since its addition. - Add Swedish translation - Use proper column name instead of attname (GH-#573) - Fix ValueError when calling prefetch_related for tracked ForeignKey fields 4.3.1 (2022-11-15) ------------------ - Confirm support for `Django 4.0` - Add Spanish translation - Add French translation - Drop Django 1.7 workaround from `select_subclasses()` - Drop support for `Django < 3.2` - Drop support for `Python 3.6` - Confirm support for `Django 4.1` 4.3.0 ----- - Never released due to packaging issues. 4.2.0 (2021-10-11) ------------------ - Add support for `Django 3.2` - Drop support for `Django 3.0` - Add support for `Python 3.10` - Added urlsafe token field. - Introduce context manager for FieldTracker state reset (GH-#491) - Fix performance regression of FieldTracker on FileField subclasses on Django 3.1+ (GH-#498) 4.1.1 (2020-12-01) ------------------ - Applied `isort` to codebase (Refs GH-#402) - Fix `TypeError` in save when model inherits from both TimeStampModel and StatusModel. (Fixes GH-465) 4.1.0 (2020-11-29) ------------------ **Breaking changes:** - `FieldTracker` now marks fields as not changed after `refresh_from_db` respecting `fields` argument (GH-#404) - `FieldTracker` now respects `update_fields` changed in overridden `save()` method (GH-#404) - `FieldTracker` now resets states after `pre_save()` and not anymore `save()` signals, possibly altering the behaviour of overridden `save()` methods (GH-#404) **Other changes:** - Update InheritanceQuerySetMixin to avoid querying too much tables - TimeStampedModel now automatically adds 'modified' field as an update_fields parameter even if it is forgotten while using save() - Replace ugettext_lazy with gettext_lazy to satisfy Django deprecation warning - Add available_objects manager to SoftDeletableModel and add deprecation warning to objects manager. - StatusModel now automatically adds 'status_changed' field during save as an update_fieldsparameter when 'status' is present in it to make sure it is not forgotten. - Update test requirements - Move tests to GitHub Actions: https://github.com/jazzband/django-model-utils/actions - Drop support for `Django 2.1` - Add support for `Python 3.9` - Add support for `Django 3.1` 4.0.0 (2019-12-11) ------------------ - Added `Choices.subset`. - Remove hacks for previously supported Django versions. (Fixes GH-390) - Dropped support for Python 2.7. (Fixes GH-393) - Dropped usage of `six` - Drop support for `Django 1.11` - Add support for `Python 3.8` - Add support for `Django 3.0` 3.2.0 (2019.06.21) ------------------- - Catch `AttributeError` for deferred abstract fields, fixes GH-331. - Update documentation to explain usage of `timeframed` model manager, fixes GH-118 - Honor `OneToOneField.parent_link=False`. - Fix handling of deferred attributes on Django 1.10+, fixes GH-278 - Fix `FieldTracker.has_changed()` and `FieldTracker.previous()` to return correct responses for deferred fields. - Add Simplified Chinese translations. - Update AutoLastModifiedField so that at instance creation it will always be set equal to created to make querying easier. Fixes GH-254 - Support `reversed` for all kinds of `Choices` objects, fixes GH-309 - Fix Model instance non picklable GH-330 - Fix patched `save` in FieldTracker - Upgrades test requirements (pytest, pytest-django, pytest-cov) and skips tox test with Python 3.5 and Django (trunk) - Add UUIDModel and UUIDField support. 3.1.2 (2018.05.09) ------------------ - Update InheritanceIterable to inherit from ModelIterable instead of BaseIterable, fixes GH-277. - Add all_objects Manager for 'SoftDeletableModel' to include soft deleted objects on queries as per issue GH-255 3.1.1 (2017.12.17) ------------------ - Update classifiers and README via GH-306, fixes GH-305 3.1.0 (2017.12.11) ------------------ - Support for Django 2.0 via GH-298, fixes GH-297 - Remove old travis script via GH-300 - Fix codecov and switch to py.test #301 3.0.0 (2017.04.13) ------------------ - Drop support for Python 2.6. - Drop support for Django 1.4, 1.5, 1.6, 1.7. - Exclude tests from the distribution, fixes GH-258. - Add support for Django 1.11 GH-269 - Add a new model to disable pre_save/post_save signals 2.6.1 (2017.01.11) ------------------ - Fix infinite recursion with multiple `MonitorField` and `defer()` or `only()` on Django 1.10+. Thanks Romain Garrigues. Merge of GH-242, fixes GH-241. - Fix `InheritanceManager` and `SoftDeletableManager` to respect `self._queryset_class` instead of hardcoding the queryset class. Merge of GH-250, fixes GH-249. - Add mixins for `SoftDeletableQuerySet` and `SoftDeletableManager`, as stated in the the documentation. - Fix `SoftDeletableModel.delete()` to use the correct database connection. Merge of GH-239. - Added boolean keyword argument `soft` to `SoftDeletableModel.delete()` that revert to default behavior when set to `False`. Merge of GH-240. - Enforced default manager in `StatusModel` to avoid manager order issues when using abstract models that redefine `objects` manager. Merge of GH-253, fixes GH-251. 2.6 (2016.09.19) ---------------- - Added `SoftDeletableModel` abstract class, its manageer `SoftDeletableManager` and queryset `SoftDeletableQuerySet`. - Fix issue with field tracker and deferred FileField for Django 1.10. 2.5.2 (2016.08.09) ------------------ - Include `runtests.py` in sdist. 2.5.1 (2016.08.03) ------------------ - Fix `InheritanceQuerySet` raising an `AttributeError` exception under Django 1.9. - Django 1.10 support regressed with changes between pre-alpha and final release; 1.10 currently not supported. 2.5 (2016.04.18) ---------------- - Drop support for Python 3.2. - Add support for Django 1.10 pre-alpha. - Track foreign keys on parent models properly when a tracker is defined on a child model. Fixes GH-214. 2.4 (2015.12.03) ---------------- - Remove `PassThroughManager`. Use Django's built-in `QuerySet.as_manager()` and/or `Manager.from_queryset()` utilities instead. - Add support for Django 1.9. 2.3.1 (2015-07-20) ------------------ - Remove all translation-related automation in `setup.py`. Fixes GH-178 and GH-179. Thanks Joe Weiss, Matt Molyneaux, and others for the reports. 2.3 (2015.07.17) ---------------- - Keep track of deferred fields on model instance instead of on FieldInstanceTracker instance. Fixes accessing deferred fields for multiple instances of a model from the same queryset. Thanks Bram Boogaard. Merge of GH-151. - Fix Django 1.7 migrations compatibility for SplitField. Thanks ad-m. Merge of GH-157; fixes GH-156. - Add German translations. - Django 1.8 compatibility. 2.2 (2014.07.31) ---------------- - Revert GH-130, restoring ability to access ``FieldTracker`` changes in overridden ``save`` methods or ``post_save`` handlers. This reopens GH-83 (inability to pickle models with ``FieldTracker``) until a solution can be found that doesn't break behavior otherwise. Thanks Brian May for the report. Fixes GH-143. 2.1.1 (2014.07.28) ------------------ - ASCII-fold all non-ASCII characters in changelog; again. Argh. Apologies to those whose names are mangled by this change. It seems that distutils makes it impossible to handle non-ASCII content reliably under Python 3 in a setup.py long_description, when the system encoding may be ASCII. Thanks Brian May for the report. Fixes GH-141. 2.1.0 (2014.07.25) ------------------ - Add support for Django's built-in migrations to ``MonitorField`` and ``StatusField``. - ``PassThroughManager`` now has support for seeing exposed methods via ``dir``, allowing `IPython`_ tab completion to be useful. Merge of GH-104, fixes GH-55. - Add pickle support for models using ``FieldTracker``. Thanks Ondrej Slintak for the report. Thanks Matthew Schinckel for the fix. Merge of GH-130, fixes GH-83. .. _IPython: https://ipython.org/ 2.0.3 (2014.03.19) ------------------- - Fix ``get_query_set`` vs ``get_queryset`` in ``PassThroughManager`` for Django <1.6. Fixes issues with related managers not filtering by relation properly. Thanks whop, Bojan Mihelac, Daniel Shapiro, and Matthew Schinckel for the report; Matthew for the fix. Merge of GH-121. - Fix ``FieldTracker`` with deferred model attributes. Thanks Michael van Tellingen. Merge of GH-115. - Fix ``InheritanceManager`` with self-referential FK; avoid infinite recursion. Thanks rsenkbeil. Merge of GH-114. 2.0.2 (2014.02.19) ------------------- - ASCII-fold all non-ASCII characters in changelog. Apologies to those whose names are mangled by this change. It seems that distutils makes it impossible to handle non-ASCII content reliably under Python 3 in a setup.py long_description, when the system encoding may be ASCII. Thanks Simone Dalla for the report. Fixes GH-113. 2.0.1 (2014.02.11) ------------------- - Fix dependency to be on "Django" rather than "django", which plays better with static PyPI mirrors. Thanks Travis Swicegood. - Fix issue with attempt to access ``__slots__`` when copying ``PassThroughManager``. Thanks Patryk Zawadzki. Merge of GH-105. - Improve ``InheritanceManager`` so any attributes added by using extra(select) will be propagated onto children. Thanks Curtis Maloney. Merge of GH-101, fixes GH-34. - Added ``InheritanceManagerMixin``, ``InheritanceQuerySetMixin``, ``PassThroughManagerMixin``, and ``QueryManagerMixin`` to allow composing their functionality with other custom manager/queryset subclasses (e.g. those in GeoDjango). Thanks Douglas Meehan! 2.0 (2014.01.06) ---------------- - BACKWARDS-INCOMPATIBLE: Indexing into a ``Choices`` instance now translates database representations to human-readable choice names, rather than simply indexing into an array of choice tuples. (Indexing into ``Choices`` was previously not documented.) If you have code that is relying on indexing or slicing ``Choices``, the simplest workaround is to change e.g. ``STATUS[1:]`` to ``list(STATUS)[1:]``. - Fixed bug with checking for field name conflicts for added query managers on `StatusModel`. - Can pass `choices_name` to `StatusField` to use a different name for choices class attribute. ``STATUS`` is used by default. - Can pass model subclasses, rather than strings, into `select_subclasses()`. Thanks Keryn Knight. Merge of GH-79. - Deepcopying a `Choices` instance no longer fails with infinite recursion in `getattr`. Thanks Leden. Merge of GH-75. - `get_subclass()` method is now available on both managers and querysets. Thanks Travis Swicegood. Merge of GH-82. - Fix bug in `InheritanceManager` with grandchild classes on Django 1.6+; `select_subclasses('child', 'child__grandchild')` would only ever get to the child class. Thanks Keryn Knight for report and proposed fix. - MonitorField now accepts a 'when' parameter. It will update only when the field changes to one of the values specified. 1.5.0 (2013.08.29) ------------------ - `Choices` now accepts option-groupings. Fixes GH-14. - `Choices` can now be added to other `Choices` or to any iterable, and can be compared for equality with itself. Thanks Tony Aldridge. (Merge of GH-76.) - `Choices` now `__contains__` its Python identifier values. Thanks Keryn Knight. (Merge of GH-69). - Fixed a bug causing ``KeyError`` when saving with the parameter ``update_fields`` in which there are untracked fields. Thanks Mikhail Silonov. (Merge of GH-70, fixes GH-71). - Fixed ``FieldTracker`` usage on inherited models. Fixes GH-57. - Added mutable field support to ``FieldTracker`` (Merge of GH-73, fixes GH-74) 1.4.0 (2013.06.03) ------------------ - Introduced ``FieldTracker`` as replacement for ``ModelTracker``, which is now deprecated. - ``PassThroughManager.for_queryset_class()`` no longer ignores superclass ``get_query_set``. Thanks Andy Freeland. - Fixed ``InheritanceManager`` bug with grandchildren in Django 1.6. Thanks CrazyCasta. - Fixed lack of ``get_FOO_display`` method for ``StatusField``. Fixes GH-41. 1.3.1 (2013.04.11) ------------------ - Added explicit default to ``BooleanField`` in tests, for Django trunk compatibility. - Fixed intermittent ``StatusField`` bug. Fixes GH-29. - Added Python 3 support. - Dropped support for Django 1.2 and 1.3. Django 1.4.2+ required. 1.3.0 (2013.03.27) ------------------ - Allow specifying default value for a ``StatusField``. Thanks Felipe Prenholato. - Fix calling ``create()`` on a ``RelatedManager`` that subclasses a dynamic ``PassThroughManager``. Thanks SeiryuZ for the report. Fixes GH-24. - Add workaround for https://code.djangoproject.com/ticket/16855 in InheritanceQuerySet to avoid overriding prior calls to ``select_related()``. Thanks ivirabyan. - Added support for arbitrary levels of model inheritance in InheritanceManager. Thanks ivirabyan. (This feature only works in Django 1.6+ due to https://code.djangoproject.com/ticket/16572). - Added ``ModelTracker`` for tracking field changes between model saves. Thanks Trey Hunner. 1.2.0 (2013.01.27) ------------------ - Moved primary development from `Bitbucket`_ to `GitHub`_. Bitbucket mirror will continue to receive updates; Bitbucket issue tracker will be closed once all issues tracked in it are resolved. .. _BitBucket: https://bitbucket.org/carljm/django-model-utils/overview .. _GitHub: https://github.com/carljm/django-model-utils/ - Removed deprecated ``ChoiceEnum``, ``InheritanceCastModel``, ``InheritanceCastManager``, and ``manager_from``. - Fixed pickling of ``PassThroughManager``. Thanks Rinat Shigapov. - Set ``use_for_related_fields = True`` on ``QueryManager``. - Added ``__len__`` method to ``Choices``. Thanks Ryan Kaskel and James Oakley. - Fixed ``InheritanceQuerySet`` on Django 1.5. Thanks Javier Garcia Sogo. 1.1.0 (2012.04.13) ------------------ - Updated AutoCreatedField, AutoLastModifiedField, MonitorField, and TimeFramedModel to use ``django.utils.timezone.now`` on Django 1.4. Thanks Donald Stufft. - Fixed annotation of InheritanceQuerysets. Thanks Jeff Elmore and Facundo Gaich. - Dropped support for Python 2.5 and Django 1.1. Both are no longer supported even for security fixes, and should not be used. - Added ``PassThroughManager.for_queryset_class()``, which fixes use of ``PassThroughManager`` with related fields. Thanks Ryan Kaskel for report and fix. - Added ``InheritanceManager.get_subclass()``. Thanks smacker. 1.0.0 (2011.06.16) ------------------ - Fixed using SplitField on an abstract base model. - Fixed issue #8, adding ``use_for_related_fields = True`` to ``InheritanceManager``. - Added ``PassThroughManager``. Thanks Paul McLanahan. - Added pending-deprecation warnings for ``InheritanceCastModel``, ``manager_from``, and Django 1.1 support. Removed documentation for the deprecated utilities. Bumped ``ChoiceEnum`` from pending-deprecation to deprecation. - Fixed issue #6, bug with InheritanceManager and descriptor fields (e.g. FileField). Thanks zyegfryed for the fix and sayane for tests. 0.6.0 (2011.02.18) ------------------ - updated SplitField to define get_prep_value rather than get_db_prep_value. This avoids deprecation warnings on Django trunk/1.3, but makes SplitField incompatible with Django versions prior to 1.2. - added InheritanceManager, a better approach to selecting subclass instances for Django 1.2+. Thanks Jeff Elmore. - added InheritanceCastManager and InheritanceCastQuerySet, to allow bulk casting of a queryset to child types. Thanks Gregor Muellegger. 0.5.0 (2010.09.24) ------------------ - added manager_from (thanks George Sakkis) - added StatusField, MonitorField, TimeFramedModel, and StatusModel (thanks Jannis Leidel) - deprecated ChoiceEnum and replaced with Choices 0.4.0 (2010.03.16) ------------------ - added SplitField - added ChoiceEnum - added South support for custom model fields 0.3.0 ----- - Added ``QueryManager`` jazzband-django-model-utils-aeef108/CODE_OF_CONDUCT.md000066400000000000000000000045071466577571100223340ustar00rootroot00000000000000# Code of Conduct As contributors and maintainers of the Jazzband projects, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in the Jazzband a harassment-free experience for everyone, regardless of the level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. Examples of unacceptable behavior by participants include: - The use of sexualized language or imagery - Personal attacks - Trolling or insulting/derogatory comments - Public or private harassment - Publishing other's private information, such as physical or electronic addresses, without explicit permission - Other unethical or unprofessional conduct The Jazzband roadies have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. By adopting this Code of Conduct, the roadies commit themselves to fairly and consistently applying these principles to every aspect of managing the jazzband projects. Roadies who do not follow or enforce the Code of Conduct may be permanently removed from the Jazzband roadies. This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the roadies at `roadies@jazzband.co`. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. Roadies are obligated to maintain confidentiality with regard to the reporter of an incident. This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.3.0, available at [https://contributor-covenant.org/version/1/3/0/][version] [homepage]: https://contributor-covenant.org [version]: https://contributor-covenant.org/version/1/3/0/ jazzband-django-model-utils-aeef108/CONTRIBUTING.rst000066400000000000000000000056351466577571100222010ustar00rootroot00000000000000Contributing ============ .. image:: https://jazzband.co/static/img/jazzband.svg :target: https://jazzband.co/ :alt: Jazzband This is a `Jazzband `_ project. By contributing you agree to abide by the `Contributor Code of Conduct `_ and follow the `guidelines `_. Below is a list of tips for submitting issues and pull requests. Submitting Issues ----------------- Issues are easier to reproduce/resolve when they have: - A pull request with a failing test demonstrating the issue - A code example that produces the issue consistently - A traceback (when applicable) Pull Requests ------------- When creating a pull request: - Write tests - Note user-facing changes in the `CHANGES`_ file - Update the documentation - Add yourself to the `AUTHORS`_ file - If you have added or changed translated strings, run ``make messages`` to update the ``.po`` translation files, and update translations for any languages you know. Then run ``make compilemessages`` to compile the ``.mo`` files. If your pull request leaves some translations incomplete, please mention that in the pull request and commit message. .. _AUTHORS: AUTHORS.rst .. _CHANGES: CHANGES.rst Translations ------------ If you are able to provide translations for a new language or to update an existing translation file, make sure to run makemessages beforehand:: python django-admin makemessages -l ISO_LANGUAGE_CODE This command will collect all translation strings from the source directory and create or update the translation file for the given language. Now open the translation file (.po) with a text-editor and start editing. After you finished editing add yourself to the list of translators. If you have created a new translation, make sure to copy the header from one of the existing translation files. Testing ------- Please add tests for your code and ensure existing tests don't break. To run the tests against your code:: python setup.py test Please use tox to test the code against supported Python and Django versions. First install tox:: pip install tox coverage To run tox and generate a coverage report (in ``htmlcov`` directory):: make test A database is required to run the tests. For convince there is a ``docker-compose.yml`` file for spinning up a database container. To start the database container run: docker-compose up -d Another way to run the tests with a sqlite database is to export the `SQLITE` variable:: export SQLITE=1 make test # or SQLITE=1 python setup.py test **Please note**: Before a pull request can be merged, all tests must pass and code/branch coverage in tests must be 100%. Code Formatting --------------- We make use of `isort`_ to sort imports. .. _isort: https://pycqa.github.io/isort/ Once it is installed you can make sure the code is properly formatted by running:: make format jazzband-django-model-utils-aeef108/LICENSE.txt000066400000000000000000000030011466577571100213440ustar00rootroot00000000000000Copyright (c) 2009-2019, Carl Meyer and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. jazzband-django-model-utils-aeef108/MANIFEST.in000066400000000000000000000003551466577571100212700ustar00rootroot00000000000000include AUTHORS.rst include CHANGES.rst include LICENSE.txt include MANIFEST.in include README.rst include requirements*.txt include Makefile tox.ini recursive-include model_utils/locale *.po *.mo graft docs recursive-include tests *.py jazzband-django-model-utils-aeef108/Makefile000066400000000000000000000012721466577571100211710ustar00rootroot00000000000000VIRTUALENV = virtualenv --python=python3 PYTHON = $(VENV)/bin/python VENV := $(shell echo $${VIRTUAL_ENV-.venv}) INSTALL_STAMP = $(VENV)/.install.stamp all: init docs test init: $(INSTALL_STAMP) $(INSTALL_STAMP): $(PYTHON) setup.py $(VENV)/bin/pip install -e . $(VENV)/bin/pip install tox coverage Sphinx touch $(INSTALL_STAMP) virtualenv: $(PYTHON) $(PYTHON): $(VIRTUALENV) $(VENV) test: init $(VENV)/bin/coverage erase $(VENV)/bin/tox $(VENV)/bin/coverage html docs: documentation documentation: init $(PYTHON) setup.py build_sphinx messages: init $(PYTHON) translations.py make compilemessages: init $(PYTHON) translations.py compile format: isort model_utils tests setup.py jazzband-django-model-utils-aeef108/README.rst000066400000000000000000000031771466577571100212260ustar00rootroot00000000000000================== django-model-utils ================== .. image:: https://jazzband.co/static/img/badge.svg :target: https://jazzband.co/ :alt: Jazzband .. image:: https://github.com/jazzband/django-model-utils/workflows/Test/badge.svg :target: https://github.com/jazzband/django-model-utils/actions .. image:: https://codecov.io/gh/jazzband/django-model-utils/branch/master/graph/badge.svg :target: https://codecov.io/gh/jazzband/django-model-utils .. image:: https://img.shields.io/pypi/v/django-model-utils.svg :target: https://pypi.python.org/pypi/django-model-utils .. image:: https://img.shields.io/pypi/pyversions/django-model-utils.svg :target: https://pypi.python.org/pypi/django-model-utils :alt: Supported Python versions .. image:: https://img.shields.io/pypi/djversions/django-model-utils.svg :target: https://pypi.org/project/django-model-utils/ :alt: Supported Django versions Django model mixins and utilities. ``django-model-utils`` supports `Django`_ 3.2+. .. _Django: https://www.djangoproject.com/ This app is available on `PyPI`_. .. _PyPI: https://pypi.python.org/pypi/django-model-utils/ Getting Help ============ Documentation for django-model-utils is available https://django-model-utils.readthedocs.io/ Contributing ============ Please file bugs and send pull requests to the `GitHub repository`_ and `issue tracker`_. See `CONTRIBUTING.rst`_ for details. .. _GitHub repository: https://github.com/jazzband/django-model-utils/ .. _issue tracker: https://github.com/jazzband/django-model-utils/issues .. _CONTRIBUTING.rst: https://github.com/jazzband/django-model-utils/blob/master/CONTRIBUTING.rst jazzband-django-model-utils-aeef108/docker-compose.yml000066400000000000000000000003031466577571100231600ustar00rootroot00000000000000services: postgres: image: postgres:13-alpine environment: POSTGRES_HOST_AUTH_METHOD: trust POSTGRES_DB: modelutils POSTGRES_USER: postgres ports: - 5432:5432 jazzband-django-model-utils-aeef108/docs/000077500000000000000000000000001466577571100204575ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/docs/Makefile000066400000000000000000000152331466577571100221230ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from https://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/django-model-utils.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django-model-utils.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/django-model-utils" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django-model-utils" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." jazzband-django-model-utils-aeef108/docs/changelog.rst000066400000000000000000000000521466577571100231350ustar00rootroot00000000000000.. changelog: .. include:: ../CHANGES.rstjazzband-django-model-utils-aeef108/docs/conf.py000066400000000000000000000176441466577571100217720ustar00rootroot00000000000000# # django-model-utils documentation build configuration file, created by # sphinx-quickstart on Wed Jul 31 22:27:07 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import importlib.metadata # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'django-model-utils' copyright = '2015, Carl Meyer' parent_dir = os.path.dirname(os.path.dirname(__file__)) # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # release = importlib.metadata.version('django-model-utils') # for example take major/minor version = '.'.join(release.split('.')[:2]) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'django-model-utilsdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'django-model-utils.tex', 'django-model-utils Documentation', 'Carl Meyer', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'django-model-utils', 'django-model-utils Documentation', ['Carl Meyer'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'django-model-utils', 'django-model-utils Documentation', 'Carl Meyer', 'django-model-utils', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False jazzband-django-model-utils-aeef108/docs/fields.rst000066400000000000000000000143571466577571100224710ustar00rootroot00000000000000Fields ====== .. _StatusField: StatusField ----------- A simple convenience for giving a model a set of "states." ``StatusField`` is a ``CharField`` subclass that expects to find a class attribute called ``STATUS`` on its model or you can pass ``choices_name`` to use a different attribute name, and uses that as its ``choices``. Also sets a default ``max_length`` of 100, and sets its default value to the first item in the ``STATUS`` choices: .. code-block:: python from model_utils.fields import StatusField from model_utils import Choices class Article(models.Model): STATUS = Choices('draft', 'published') # ... status = StatusField() (The ``STATUS`` class attribute does not have to be a :ref:`Choices` instance, it can be an ordinary list of two-tuples). Using a different name for the model's choices class attribute .. code-block:: python from model_utils.fields import StatusField from model_utils import Choices class Article(models.Model): ANOTHER_CHOICES = Choices('draft', 'published') # ... another_field = StatusField(choices_name='ANOTHER_CHOICES') ``StatusField`` does not set ``db_index=True`` automatically; if you expect to frequently filter on your status field (and it will have enough selectivity to make an index worthwhile) you may want to add this yourself. .. _MonitorField: MonitorField ------------ A ``DateTimeField`` subclass that monitors another field on the model, and updates itself to the current date-time whenever the monitored field changes: .. code-block:: python from model_utils.fields import MonitorField, StatusField class Article(models.Model): STATUS = Choices('draft', 'published') status = StatusField() status_changed = MonitorField(monitor='status') (A ``MonitorField`` can monitor any type of field for changes, not only a ``StatusField``.) If a list is passed to the ``when`` parameter, the field will only update when it matches one of the specified values: .. code-block:: python from model_utils.fields import MonitorField, StatusField class Article(models.Model): STATUS = Choices('draft', 'published') status = StatusField() published_at = MonitorField(monitor='status', when=['published']) SplitField ---------- A ``TextField`` subclass that automatically pulls an excerpt out of its content (based on a "split here" marker or a default number of initial paragraphs) and stores both its content and excerpt values in the database. A ``SplitField`` is easy to add to any model definition: .. code-block:: python from django.db import models from model_utils.fields import SplitField class Article(models.Model): title = models.CharField(max_length=100) body = SplitField() ``SplitField`` automatically creates an extra non-editable field ``_body_excerpt`` to store the excerpt. This field doesn't need to be accessed directly; see below. Accessing a SplitField on a model ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When accessing an attribute of a model that was declared as a ``SplitField``, a ``SplitText`` object is returned. The ``SplitText`` object has three attributes: ``content``: The full field contents. ``excerpt``: The excerpt of ``content`` (read-only). ``has_more``: True if the excerpt and content are different, False otherwise. This object also has a ``__unicode__`` method that returns the full content, allowing ``SplitField`` attributes to appear in templates without having to access ``content`` directly. Assuming the ``Article`` model above: .. code-block:: pycon >>> a = Article.objects.all()[0] >>> a.body.content u'some text\n\n\n\nmore text' >>> a.body.excerpt u'some text\n' >>> unicode(a.body) u'some text\n\n\n\nmore text' Assignment to ``a.body`` is equivalent to assignment to ``a.body.content``. .. note:: a.body.excerpt is only updated when a.save() is called Customized excerpting ~~~~~~~~~~~~~~~~~~~~~ By default, ``SplitField`` looks for the marker ```` alone on a line and takes everything before that marker as the excerpt. This marker can be customized by setting the ``SPLIT_MARKER`` setting. If no marker is found in the content, the first two paragraphs (where paragraphs are blocks of text separated by a blank line) are taken to be the excerpt. This number can be customized by setting the ``SPLIT_DEFAULT_PARAGRAPHS`` setting. UUIDField ---------- A ``UUIDField`` subclass that provides an UUID field. You can add this field to any model definition. With the param ``primary_key`` you can set if this field is the primary key for the model, default is True. Param ``version`` is an integer that set default UUID version. Versions 1,3,4 and 5 are supported, default is 4. If ``editable`` is set to false the field will not be displayed in the admin or any other ModelForm, default is False. .. code-block:: python from django.db import models from model_utils.fields import UUIDField class MyAppModel(models.Model): uuid = UUIDField(primary_key=True, version=4, editable=False) UrlsafeTokenField ----------------- A ``CharField`` subclass that provides random token generating using python's ``secrets.token_urlsafe`` as default value. If ``editable`` is set to false the field will not be displayed in the admin or any other ModelForm, default is False. ``max_length`` specifies the maximum length of the token. The default value is 128. .. code-block:: python from django.db import models from model_utils.fields import UrlsafeTokenField class MyAppModel(models.Model): uuid = UrlsafeTokenField(editable=False, max_length=128) You can provide your custom token generator using the ``factory`` argument. ``factory`` should be callable. It will raise ``TypeError`` if it is not callable. ``factory`` is called with ``max_length`` argument to generate the token, and should return a string of specified maximum length. .. code-block:: python import uuid from django.db import models from model_utils.fields import UrlsafeTokenField def _token_factory(max_length): return uuid.uuid4().hex class MyAppModel(models.Model): uuid = UrlsafeTokenField(max_length=32, factory=_token_factory) jazzband-django-model-utils-aeef108/docs/index.rst000066400000000000000000000010721466577571100223200ustar00rootroot00000000000000================== django-model-utils ================== Django model mixins and utilities. Contents ======== .. toctree:: :maxdepth: 3 setup fields models managers utilities changelog Contributing ============ Please file bugs and send pull requests to the `GitHub repository`_ and `issue tracker`_. .. _GitHub repository: https://github.com/jazzband/django-model-utils/ .. _issue tracker: https://github.com/jazzband/django-model-utils/issues Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` jazzband-django-model-utils-aeef108/docs/make.bat000066400000000000000000000145241466577571100220720ustar00rootroot00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.https://sphinx-doc.org/ exit /b 1 ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\django-model-utils.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\django-model-utils.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :end jazzband-django-model-utils-aeef108/docs/managers.rst000066400000000000000000000135011466577571100230060ustar00rootroot00000000000000Model Managers ============== InheritanceManager ------------------ This manager (`contributed by Jeff Elmore`_) should be attached to a base model class in a model-inheritance tree. It allows queries on that base model to return heterogeneous results of the actual proper subtypes, without any additional queries. For instance, if you have a ``Place`` model with subclasses ``Restaurant`` and ``Bar``, you may want to query all Places: .. code-block:: python nearby_places = Place.objects.filter(location='here') But when you iterate over ``nearby_places``, you'll get only ``Place`` instances back, even for objects that are "really" ``Restaurant`` or ``Bar``. If you attach an ``InheritanceManager`` to ``Place``, you can just call the ``select_subclasses()`` method on the ``InheritanceManager`` or any ``QuerySet`` from it, and the resulting objects will be instances of ``Restaurant`` or ``Bar``: .. code-block:: python from model_utils.managers import InheritanceManager class Place(models.Model): # ... objects = InheritanceManager() class Restaurant(Place): # ... class Bar(Place): # ... nearby_places = Place.objects.filter(location='here').select_subclasses() for place in nearby_places: # "place" will automatically be an instance of Place, Restaurant, or Bar The database query performed will have an extra join for each subclass; if you want to reduce the number of joins and you only need particular subclasses to be returned as their actual type, you can pass subclass names to ``select_subclasses()``, much like the built-in ``select_related()`` method: .. code-block:: python nearby_places = Place.objects.select_subclasses("restaurant") # restaurants will be Restaurant instances, bars will still be Place instances nearby_places = Place.objects.select_subclasses("restaurant", "bar") # all Places will be converted to Restaurant and Bar instances. It is also possible to use the subclasses themselves as arguments to ``select_subclasses``, leaving it to calculate the relationship for you: .. code-block:: python nearby_places = Place.objects.select_subclasses(Restaurant) # restaurants will be Restaurant instances, bars will still be Place instances nearby_places = Place.objects.select_subclasses(Restaurant, Bar) # all Places will be converted to Restaurant and Bar instances. It is even possible to mix and match the two: .. code-block:: python nearby_places = Place.objects.select_subclasses(Restaurant, "bar") # all Places will be converted to Restaurant and Bar instances. ``InheritanceManager`` also provides a subclass-fetching alternative to the ``get()`` method: .. code-block:: python place = Place.objects.get_subclass(id=some_id) # "place" will automatically be an instance of Place, Restaurant, or Bar If you don't explicitly call ``select_subclasses()`` or ``get_subclass()``, an ``InheritanceManager`` behaves identically to a normal ``Manager``; so it's safe to use as your default manager for the model. .. _contributed by Jeff Elmore: https://jeffelmore.org/2010/11/11/automatic-downcasting-of-inherited-models-in-django/ JoinQueryset ------------ A ``JoinQueryset`` will create a temporary table containing its own query result and join that temporary table with the model it is querying. This can be advantageous if you have to page through your entire DB and using django's slice mechanism to do that. ``LIMIT .. OFFSET ..`` becomes slower the bigger offset you use. .. code-block:: python sliced_qs = Place.objects.all()[2000:2010] qs = sliced_qs.join() # qs contains 10 objects, and there will be a much smaller performance hit # for paging through all of first 2000 objects. Alternatively, you can give it another queryset and ``JoinQueryset`` will create a temporary table containing the result of the given queryset and join that temporary table to itself. This can work as a more performant alternative to using django's ``__in`` as described in the following (`StackExchange answer`_). .. code-block:: python big_qs = Restaurant.objects.filter(menu='vegetarian') qs = Country.objects.filter(country_code='SE').join(big_qs) .. _StackExchange answer: https://dba.stackexchange.com/questions/91247/optimizing-a-postgres-query-with-a-large-in You can create a manager that produces ``JoinQueryset`` instances using ``JoinQueryset.as_manager()``. .. _QueryManager: QueryManager ------------ Many custom model managers do nothing more than return a QuerySet that is filtered in some way. ``QueryManager`` allows you to express this pattern with a minimum of boilerplate: .. code-block:: python from django.db import models from model_utils.managers import QueryManager class Post(models.Model): ... published = models.BooleanField() pub_date = models.DateField() ... objects = models.Manager() public = QueryManager(published=True).order_by('-pub_date') The kwargs passed to ``QueryManager`` will be passed as-is to the ``QuerySet.filter()`` method. You can also pass a ``Q`` object to ``QueryManager`` to express more complex conditions. Note that you can set the ordering of the ``QuerySet`` returned by the ``QueryManager`` by chaining a call to ``.order_by()`` on the ``QueryManager`` (this is not required). SoftDeletableManager -------------------- Returns only model instances that have the ``is_removed`` field set to False. Uses ``SoftDeletableQuerySet``, which ensures model instances won't be removed in bulk, but they will be marked as removed instead. Mixins ------ Each of the above manager classes has a corresponding mixin that can be used to add functionality to any manager. Note that any manager class using ``InheritanceManagerMixin`` must return a ``QuerySet`` class using ``InheritanceQuerySetMixin`` from its ``get_queryset`` method. jazzband-django-model-utils-aeef108/docs/models.rst000066400000000000000000000064271466577571100225050ustar00rootroot00000000000000Models ====== TimeFramedModel --------------- An abstract base class for any model that expresses a time-range. Adds ``start`` and ``end`` nullable DateTimeFields, and provides a new ``timeframed`` manager on the subclass whose queryset pre-filters results to only include those which have a ``start`` which is not in the future, and an ``end`` which is not in the past. If either ``start`` or ``end`` is ``null``, the manager will include it. .. code-block:: python from model_utils.models import TimeFramedModel from datetime import datetime, timedelta class Post(TimeFramedModel): pass p = Post() p.start = datetime.utcnow() - timedelta(days=1) p.end = datetime.utcnow() + timedelta(days=7) p.save() # this query will return the above Post instance: Post.timeframed.all() p.start = None p.end = None p.save() # this query will also return the above Post instance, because # the `start` and/or `end` are NULL. Post.timeframed.all() p.start = datetime.utcnow() + timedelta(days=7) p.save() # this query will NOT return our Post instance, because # the start date is in the future. Post.timeframed.all() TimeStampedModel ---------------- This abstract base class just provides self-updating ``created`` and ``modified`` fields on any model that inherits from it. StatusModel ----------- Pulls together :ref:`StatusField`, :ref:`MonitorField` and :ref:`QueryManager` into an abstract base class for any model with a "status." Just provide a ``STATUS`` class-attribute (a :ref:`Choices` object or a list of two-tuples), and your model will have a ``status`` field with those choices, a ``status_changed`` field containing the date-time the ``status`` was last changed, and a manager for each status that returns objects with that status only: .. code-block:: python from model_utils.models import StatusModel from model_utils import Choices class Article(StatusModel): STATUS = Choices('draft', 'published') # ... a = Article() a.status = Article.STATUS.published # this save will update a.status_changed a.save() # this query will only return published articles: Article.published.all() SoftDeletableModel ------------------ This abstract base class just provides a field ``is_removed`` which is set to True instead of removing the instance. Entities returned in manager ``available_objects`` are limited to not-deleted instances. Note that relying on the default ``objects`` manager to filter out not-deleted instances is deprecated. ``objects`` will include deleted objects in a future release. Until then, the recommended course of action is to use the manager ``all_objects`` when you want to include all instances. UUIDModel ------------------ This abstract base class provides ``id`` field on any model that inherits from it which will be the primary key. If you dont want to set ``id`` as primary key or change the field name, you can override it with our `UUIDField`_ Also you can override the default uuid version. Versions 1,3,4 and 5 are now supported. .. code-block:: python from model_utils.models import UUIDModel class MyAppModel(UUIDModel): pass .. _`UUIDField`: https://github.com/jazzband/django-model-utils/blob/master/docs/fields.rst#uuidfield jazzband-django-model-utils-aeef108/docs/setup.rst000066400000000000000000000007431466577571100223550ustar00rootroot00000000000000===== Setup ===== Installation ============ Install from PyPI with ``pip``:: pip install django-model-utils To use ``django-model-utils`` in your Django project, just import and use the utility classes described in this documentation; there is no need to modify your ``INSTALLED_APPS`` setting. Dependencies ============ ``django-model-utils`` supports `Django`_ 3.2+ (latest bugfix release in each series only) on Python 3.7+. .. _Django: https://www.djangoproject.com/ jazzband-django-model-utils-aeef108/docs/utilities.rst000066400000000000000000000334531466577571100232340ustar00rootroot00000000000000======================= Miscellaneous Utilities ======================= .. _Choices: ``Choices`` =========== .. note:: Django 3.0 adds `enumeration types `__. These provide most of the same features as ``Choices``. ``Choices`` provides some conveniences for setting ``choices`` on a Django model field: .. code-block:: python from model_utils import Choices class Article(models.Model): STATUS = Choices('draft', 'published') status = models.CharField(choices=STATUS, default=STATUS.draft, max_length=20) A ``Choices`` object is initialized with any number of choices. In the simplest case, each choice is a string; that string will be used both as the database representation of the choice, and the human-readable representation. Note that you can access options as attributes on the ``Choices`` object: ``STATUS.draft``. But you may want your human-readable versions translated, in which case you need to separate the human-readable version from the DB representation. In this case you can provide choices as two-tuples: .. code-block:: python from model_utils import Choices class Article(models.Model): STATUS = Choices(('draft', _('draft')), ('published', _('published'))) status = models.CharField(choices=STATUS, default=STATUS.draft, max_length=20) But what if your database representation of choices is constrained in a way that would hinder readability of your code? For instance, you may need to use an ``IntegerField`` rather than a ``CharField``, or you may want the database to order the values in your field in some specific way. In this case, you can provide your choices as triples, where the first element is the database representation, the second is a valid Python identifier you will use in your code as a constant, and the third is the human-readable version: .. code-block:: python from model_utils import Choices class Article(models.Model): STATUS = Choices((0, 'draft', _('draft')), (1, 'published', _('published'))) status = models.IntegerField(choices=STATUS, default=STATUS.draft) You can index into a ``Choices`` instance to translate a database representation to its display name: .. code-block:: python status_display = Article.STATUS[article.status] Option groups can also be used with ``Choices``; in that case each argument is a tuple consisting of the option group name and a list of options, where each option in the list is either a string, a two-tuple, or a triple as outlined above. For example: .. code-block:: python from model_utils import Choices class Article(models.Model): STATUS = Choices(('Visible', ['new', 'archived']), ('Invisible', ['draft', 'deleted'])) Choices can be concatenated with the ``+`` operator, both to other Choices instances and other iterable objects that could be converted into Choices: .. code-block:: python from model_utils import Choices GENERIC_CHOICES = Choices((0, 'draft', _('draft')), (1, 'published', _('published'))) class Article(models.Model): STATUS = GENERIC_CHOICES + [(2, 'featured', _('featured'))] status = models.IntegerField(choices=STATUS, default=STATUS.draft) Should you wish to provide a subset of choices for a field, for instance, you have a form class to set some model instance to a failed state, and only wish to show the user the failed outcomes from which to select, you can use the ``subset`` method: .. code-block:: python from model_utils import Choices OUTCOMES = Choices( (0, 'success', _('Successful')), (1, 'user_cancelled', _('Cancelled by the user')), (2, 'admin_cancelled', _('Cancelled by an admin')), ) FAILED_OUTCOMES = OUTCOMES.subset('user_cancelled', 'admin_cancelled') The ``choices`` attribute on the model field can then be set to ``FAILED_OUTCOMES``, thus allowing the subset to be defined in close proximity to the definition of all the choices, and reused elsewhere as required. Field Tracker ============= A ``FieldTracker`` can be added to a model to track changes in model fields. A ``FieldTracker`` allows querying for field changes since a model instance was last saved. An example of applying ``FieldTracker`` to a model: .. code-block:: python from django.db import models from model_utils import FieldTracker class Post(models.Model): title = models.CharField(max_length=100) body = models.TextField() tracker = FieldTracker() .. note:: ``django-model-utils`` 1.3.0 introduced the ``ModelTracker`` object for tracking changes to model field values. Unfortunately ``ModelTracker`` suffered from some serious flaws in its handling of ``ForeignKey`` fields, potentially resulting in many extra database queries if a ``ForeignKey`` field was tracked. In order to avoid breaking API backwards-compatibility, ``ModelTracker`` retains the previous behavior but is deprecated, and ``FieldTracker`` has been introduced to provide better ``ForeignKey`` handling. All uses of ``ModelTracker`` should be replaced by ``FieldTracker``. Summary of differences between ``ModelTracker`` and ``FieldTracker``: * The previous value returned for a tracked ``ForeignKey`` field will now be the raw ID rather than the full object (avoiding extra database queries). (GH-43) * The ``changed()`` method no longer returns the empty dictionary for all unsaved instances; rather, ``None`` is considered to be the initial value of all fields if the model has never been saved, thus ``changed()`` on an unsaved instance will return a dictionary containing all fields whose current value is not ``None``. * The ``has_changed()`` method no longer crashes after an object's first save. (GH-53). Accessing a field tracker ------------------------- There are multiple methods available for checking for changes in model fields. previous ~~~~~~~~ Returns the value of the given field during the last save: .. code-block:: pycon >>> a = Post.objects.create(title='First Post') >>> a.title = 'Welcome' >>> a.tracker.previous('title') u'First Post' Returns ``None`` when the model instance isn't saved yet. If a field is `deferred`_, calling ``previous()`` will load the previous value from the database. .. _deferred: https://docs.djangoproject.com/en/2.0/ref/models/querysets/#defer has_changed ~~~~~~~~~~~ Returns ``True`` if the given field has changed since the last save. The ``has_changed`` method expects a single field: .. code-block:: pycon >>> a = Post.objects.create(title='First Post') >>> a.title = 'Welcome' >>> a.tracker.has_changed('title') True >>> a.tracker.has_changed('body') False The ``has_changed`` method relies on ``previous`` to determine whether a field's values has changed. If a field is `deferred`_ and has been assigned locally, calling ``has_changed()`` will load the previous value from the database to perform the comparison. changed ~~~~~~~ Returns a dictionary of all fields that have been changed since the last save and the values of the fields during the last save: .. code-block:: pycon >>> a = Post.objects.create(title='First Post') >>> a.title = 'Welcome' >>> a.body = 'First post!' >>> a.tracker.changed() {'title': 'First Post', 'body': ''} The ``changed`` method relies on ``has_changed`` to determine which fields have changed. Tracking specific fields ------------------------ A fields parameter can be given to ``FieldTracker`` to limit tracking to specific fields: .. code-block:: python from django.db import models from model_utils import FieldTracker class Post(models.Model): title = models.CharField(max_length=100) body = models.TextField() title_tracker = FieldTracker(fields=['title']) An example using the model specified above: .. code-block:: pycon >>> a = Post.objects.create(title='First Post') >>> a.body = 'First post!' >>> a.title_tracker.changed() {'title': None} Tracking Foreign Key Fields --------------------------- It should be noted that a generic FieldTracker tracks Foreign Keys by db_column name, rather than model field name, and would be accessed as follows: .. code-block:: python from django.db import models from model_utils import FieldTracker class Parent(models.Model): name = models.CharField(max_length=64) class Child(models.Model): name = models.CharField(max_length=64) parent = models.ForeignKey(Parent) tracker = FieldTracker() .. code-block:: pycon >>> p = Parent.objects.create(name='P') >>> c = Child.objects.create(name='C', parent=p) >>> c.tracker.has_changed('parent_id') To find the db_column names of your model (using the above example): .. code-block:: pycon >>> for field in Child._meta.fields: field.get_attname_column() ('id', 'id') ('name', 'name') ('parent_id', 'parent_id') The model field name *may* be used when tracking with a specific tracker: .. code-block:: python specific_tracker = FieldTracker(fields=['parent']) But according to issue #195 this is not recommended for accessing Foreign Key Fields. Checking changes using signals ------------------------------ The field tracker methods may also be used in ``pre_save`` and ``post_save`` signal handlers to identify field changes on model save. .. NOTE:: Due to the implementation of ``FieldTracker``, ``post_save`` signal handlers relying on field tracker methods should only be registered after model creation. FieldTracker implementation details ----------------------------------- .. code-block:: python from django.db import models from model_utils import FieldTracker, TimeStampedModel class MyModel(TimeStampedModel): name = models.CharField(max_length=64) tracker = FieldTracker() def save(self, *args, **kwargs): """ Automatically add "modified" to update_fields.""" update_fields = kwargs.get('update_fields') if update_fields is not None: kwargs['update_fields'] = set(update_fields) | {'modified'} super().save(*args, **kwargs) # [...] instance = MyModel.objects.first() instance.name = 'new' instance.save(update_fields={'name'}) This is how ``FieldTracker`` tracks field changes on ``instance.save`` call. 1. In ``class_prepared`` handler ``FieldTracker`` patches ``save_base``, ``refresh_from_db`` and ``__init__`` methods to reset initial state for tracked fields. 2. In the patched ``__init__`` method ``FieldTracker`` saves initial values for tracked fields. 3. ``MyModel.save`` changes ``update_fields`` in order to store auto updated ``modified`` timestamp. Complete list of saved fields is now known. 4. ``Model.save`` does nothing interesting except calling ``save_base``. 5. Decorated ``save_base()`` method calls ``super().save_base`` and all fields that have values different to initial are considered as changed. 6. ``Model.save_base`` sends ``pre_save`` signal, saves instance to database and sends ``post_save`` signal. All ``pre_save/post_save`` receivers can query ``instance.tracker`` for a set of changed fields etc. 7. After ``Model.save_base`` return ``FieldTracker`` resets initial state for updated fields (if no ``update_fields`` passed - whole initial state is reset). 8. ``instance.refresh_from_db()`` call causes initial state reset like for ``save_base()``. When FieldTracker resets fields state ------------------------------------- By the definition: .. NOTE:: * Field value *is changed* if it differs from current database value. * Field value *was changed* if value has changed in database and field state didn't reset. .. code-block:: python instance = Tracked.objects.get(pk=1) # name not changed instance.name += '_changed' # name is changed instance.save() # name is not changed again Current implementation resets fields state after ``post_save`` signals emitting. This is convenient for "outer" code like in example above, but does not help when model ``save`` method is overridden. .. code-block:: python class MyModel(models.Model) name = models.CharField(max_length=64) tracker = FieldTracker() def save(self): # erroneous implementation self.name = self.name.replace(' ', '_') name_changed = self.tracker.has_changed('name') super().save() # changed state has been reset here, so we need to store previous state somewhere else if name_changed: do_something_about_it() ``FieldTracker`` provides a context manager interface to postpone fields state reset in complicate situations. * Fields state resets after exiting from outer-most context * By default, all fields are reset, but field list can be provided * Fields are counted separately depending on field list passed to context managers * Tracker can be used as decorator * Different instances have their own context state * Different trackers in same instance have separate context state .. code-block:: python class MyModel(models.Model) name = models.CharField(max_length=64) tracker = FieldTracker() def save(self): # correct implementation self.name = self.name.replace(' ', '_') with self.tracker: super().save() # changed state reset is postponed if self.tracker.has_changed('name'): do_something_about_it() # Decorator example @tracker def save(self): ... # Restrict a set of fields to reset here @tracker(fields=('name')) def save(self): ... # Context manager with field list def save(self): with self.tracker('name'): ... jazzband-django-model-utils-aeef108/model_utils/000077500000000000000000000000001466577571100220475ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/model_utils/__init__.py000066400000000000000000000005761466577571100241700ustar00rootroot00000000000000import importlib.metadata from .choices import Choices from .tracker import FieldTracker, ModelTracker try: __version__ = importlib.metadata.version('django-model-utils') except importlib.metadata.PackageNotFoundError: # pragma: no cover # package is not installed __version__ = None # type: ignore[assignment] __all__ = ("Choices", "FieldTracker", "ModelTracker") jazzband-django-model-utils-aeef108/model_utils/choices.py000066400000000000000000000221421466577571100240370ustar00rootroot00000000000000from __future__ import annotations import copy from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast, overload T = TypeVar("T") if TYPE_CHECKING: from collections.abc import Iterable, Iterator, Sequence # The type aliases defined here are evaluated when the django-stubs mypy plugin # loads this module, so they must be able to execute under the lowest supported # Python VM: # - typing.List, typing.Tuple become obsolete in Pyton 3.9 # - typing.Union becomes obsolete in Pyton 3.10 from typing import List, Tuple, Union from django_stubs_ext import StrOrPromise # The type argument 'T' to 'Choices' is the database representation type. _Double = Tuple[T, StrOrPromise] _Triple = Tuple[T, str, StrOrPromise] _Group = Tuple[StrOrPromise, Sequence["_Choice[T]"]] _Choice = Union[_Double[T], _Triple[T], _Group[T]] # Choices can only be given as a single string if 'T' is 'str'. _GroupStr = Tuple[StrOrPromise, Sequence["_ChoiceStr"]] _ChoiceStr = Union[str, _Double[str], _Triple[str], _GroupStr] # Note that we only accept lists and tuples in groups, not arbitrary sequences. # However, annotating it as such causes many problems. _DoubleRead = Union[_Double[T], Tuple[StrOrPromise, Iterable["_DoubleRead[T]"]]] _DoubleCollector = List[Union[_Double[T], Tuple[StrOrPromise, "_DoubleCollector[T]"]]] _TripleCollector = List[Union[_Triple[T], Tuple[StrOrPromise, "_TripleCollector[T]"]]] class Choices(Generic[T]): """ A class to encapsulate handy functionality for lists of choices for a Django model field. Each argument to ``Choices`` is a choice, represented as either a string, a two-tuple, or a three-tuple. If a single string is provided, that string is used as the database representation of the choice as well as the human-readable presentation. If a two-tuple is provided, the first item is used as the database representation and the second the human-readable presentation. If a triple is provided, the first item is the database representation, the second a valid Python identifier that can be used as a readable label in code, and the third the human-readable presentation. This is most useful when the database representation must sacrifice readability for some reason: to achieve a specific ordering, to use an integer rather than a character field, etc. Regardless of what representation of each choice is originally given, when iterated over or indexed into, a ``Choices`` object behaves as the standard Django choices list of two-tuples. If the triple form is used, the Python identifier names can be accessed as attributes on the ``Choices`` object, returning the database representation. (If the single or two-tuple forms are used and the database representation happens to be a valid Python identifier, the database representation itself is available as an attribute on the ``Choices`` object, returning itself.) Option groups can also be used with ``Choices``; in that case each argument is a tuple consisting of the option group name and a list of options, where each option in the list is either a string, a two-tuple, or a triple as outlined above. """ @overload def __init__(self: Choices[str], *choices: _ChoiceStr): ... @overload def __init__(self, *choices: _Choice[T]): ... def __init__(self, *choices: _ChoiceStr | _Choice[T]): # list of choices expanded to triples - can include optgroups self._triples: _TripleCollector[T] = [] # list of choices as (db, human-readable) - can include optgroups self._doubles: _DoubleCollector[T] = [] # dictionary mapping db representation to human-readable self._display_map: dict[T, StrOrPromise | list[_Triple[T]]] = {} # dictionary mapping Python identifier to db representation self._identifier_map: dict[str, T] = {} # set of db representations self._db_values: set[T] = set() self._process(choices) def _store( self, triple: tuple[T, str, StrOrPromise], triple_collector: _TripleCollector[T], double_collector: _DoubleCollector[T] ) -> None: self._identifier_map[triple[1]] = triple[0] self._display_map[triple[0]] = triple[2] self._db_values.add(triple[0]) triple_collector.append(triple) double_collector.append((triple[0], triple[2])) def _process( self, choices: Iterable[_ChoiceStr | _Choice[T]], triple_collector: _TripleCollector[T] | None = None, double_collector: _DoubleCollector[T] | None = None ) -> None: if triple_collector is None: triple_collector = self._triples if double_collector is None: double_collector = self._doubles def store(c: tuple[Any, str, StrOrPromise]) -> None: self._store(c, triple_collector, double_collector) for choice in choices: # The type inference is not very accurate here: # - we lied in the type aliases, stating groups contain an arbitrary Sequence # rather than only list or tuple # - there is no way to express that _ChoiceStr is only used when T=str # - mypy 1.9.0 doesn't narrow types based on the value of len() if isinstance(choice, (list, tuple)): if len(choice) == 3: store(choice) elif len(choice) == 2: if isinstance(choice[1], (list, tuple)): # option group group_name = choice[0] subchoices = choice[1] tc: _TripleCollector[T] = [] triple_collector.append((group_name, tc)) dc: _DoubleCollector[T] = [] double_collector.append((group_name, dc)) self._process(subchoices, tc, dc) else: store((choice[0], cast(str, choice[0]), cast('StrOrPromise', choice[1]))) else: raise ValueError( "Choices can't take a list of length %s, only 2 or 3" % len(choice) ) else: store((choice, choice, choice)) def __len__(self) -> int: return len(self._doubles) def __iter__(self) -> Iterator[_DoubleRead[T]]: return iter(self._doubles) def __reversed__(self) -> Iterator[_DoubleRead[T]]: return reversed(self._doubles) def __getattr__(self, attname: str) -> T: try: return self._identifier_map[attname] except KeyError: raise AttributeError(attname) def __getitem__(self, key: T) -> StrOrPromise | Sequence[_Triple[T]]: return self._display_map[key] @overload def __add__(self: Choices[str], other: Choices[str] | Iterable[_ChoiceStr]) -> Choices[str]: ... @overload def __add__(self, other: Choices[T] | Iterable[_Choice[T]]) -> Choices[T]: ... def __add__(self, other: Choices[Any] | Iterable[_ChoiceStr | _Choice[Any]]) -> Choices[Any]: other_args: list[Any] if isinstance(other, self.__class__): other_args = other._triples else: other_args = list(other) return Choices(*(self._triples + other_args)) @overload def __radd__(self: Choices[str], other: Iterable[_ChoiceStr]) -> Choices[str]: ... @overload def __radd__(self, other: Iterable[_Choice[T]]) -> Choices[T]: ... def __radd__(self, other: Iterable[_ChoiceStr] | Iterable[_Choice[T]]) -> Choices[Any]: # radd is never called for matching types, so we don't check here other_args = list(other) # The exact type of 'other' depends on our type argument 'T', which # is expressed in the overloading, but lost within this method body. return Choices(*(other_args + self._triples)) # type: ignore[arg-type] def __eq__(self, other: object) -> bool: if isinstance(other, self.__class__): return self._triples == other._triples return False def __repr__(self) -> str: return '{}({})'.format( self.__class__.__name__, ', '.join("%s" % repr(i) for i in self._triples) ) def __contains__(self, item: T) -> bool: return item in self._db_values def __deepcopy__(self, memo: dict[int, Any] | None) -> Choices[T]: args: list[Any] = copy.deepcopy(self._triples, memo) return self.__class__(*args) def subset(self, *new_identifiers: str) -> Choices[T]: identifiers = set(self._identifier_map.keys()) if not identifiers.issuperset(new_identifiers): raise ValueError( 'The following identifiers are not present: %s' % identifiers.symmetric_difference(new_identifiers), ) args: list[Any] = [ choice for choice in self._triples if choice[1] in new_identifiers ] return self.__class__(*args) jazzband-django-model-utils-aeef108/model_utils/fields.py000066400000000000000000000311461466577571100236740ustar00rootroot00000000000000from __future__ import annotations import secrets import uuid from collections.abc import Sequence from typing import TYPE_CHECKING, Any, Union from django.conf import settings from django.core.exceptions import ValidationError from django.db import models from django.utils.timezone import now if TYPE_CHECKING: from collections.abc import Callable, Iterable from datetime import date, datetime DateTimeFieldBase = models.DateTimeField[Union[str, datetime, date], datetime] else: DateTimeFieldBase = models.DateTimeField DEFAULT_CHOICES_NAME = 'STATUS' class AutoCreatedField(DateTimeFieldBase): """ A DateTimeField that automatically populates itself at object creation. By default, sets editable=False, default=datetime.now. """ def __init__(self, *args: Any, **kwargs: Any): kwargs.setdefault('editable', False) kwargs.setdefault('default', now) super().__init__(*args, **kwargs) class AutoLastModifiedField(AutoCreatedField): """ A DateTimeField that updates itself on each save() of the model. By default, sets editable=False and default=datetime.now. """ def get_default(self) -> datetime: """Return the default value for this field.""" if not hasattr(self, "_default"): self._default = super().get_default() return self._default def pre_save(self, model_instance: models.Model, add: bool) -> datetime: value = now() if add: current_value = getattr(model_instance, self.attname, self.get_default()) if current_value != self.get_default(): # when creating an instance and the modified date is set # don't change the value, assume the developer wants that # control. value = getattr(model_instance, self.attname) else: for field in model_instance._meta.get_fields(): if isinstance(field, AutoCreatedField): value = getattr(model_instance, field.name) break setattr(model_instance, self.attname, value) return value class StatusField(models.CharField): """ A CharField that looks for a ``STATUS`` class-attribute and automatically uses that as ``choices``. The first option in ``STATUS`` is set as the default. Also has a default max_length so you don't have to worry about setting that. Also features a ``no_check_for_status`` argument to make sure South can handle this field when it freezes a model. """ def __init__( self, *args: Any, no_check_for_status: bool = False, choices_name: str = DEFAULT_CHOICES_NAME, **kwargs: Any ): kwargs.setdefault('max_length', 100) self.check_for_status = not no_check_for_status self.choices_name = choices_name super().__init__(*args, **kwargs) def prepare_class(self, sender: type[models.Model], **kwargs: Any) -> None: if not sender._meta.abstract and self.check_for_status: assert hasattr(sender, self.choices_name), \ "To use StatusField, the model '%s' must have a %s choices class attribute." \ % (sender.__name__, self.choices_name) self.choices = getattr(sender, self.choices_name) if not self.has_default(): self.default = tuple(getattr(sender, self.choices_name))[0][0] # set first as default def contribute_to_class(self, cls: type[models.Model], name: str, *args: Any, **kwargs: Any) -> None: models.signals.class_prepared.connect(self.prepare_class, sender=cls) # we don't set the real choices until class_prepared (so we can rely on # the STATUS class attr being available), but we need to set some dummy # choices now so the super method will add the get_FOO_display method self.choices = [(0, 'dummy')] super().contribute_to_class(cls, name, *args, **kwargs) def deconstruct(self) -> tuple[str, str, Sequence[Any], dict[str, Any]]: name, path, args, kwargs = super().deconstruct() kwargs['no_check_for_status'] = True return name, path, args, kwargs class MonitorField(DateTimeFieldBase): """ A DateTimeField that monitors another field on the same model and sets itself to the current date/time whenever the monitored field changes. """ def __init__(self, *args: Any, monitor: str, when: Iterable[Any] | None = None, **kwargs: Any): default = None if kwargs.get("null") else now kwargs.setdefault('default', default) self.monitor = monitor self.when = None if when is None else set(when) super().__init__(*args, **kwargs) def contribute_to_class(self, cls: type[models.Model], name: str, *args: Any, **kwargs: Any) -> None: self.monitor_attname = '_monitor_%s' % name models.signals.post_init.connect(self._save_initial, sender=cls) super().contribute_to_class(cls, name, *args, **kwargs) def get_monitored_value(self, instance: models.Model) -> Any: return getattr(instance, self.monitor) def _save_initial(self, sender: type[models.Model], instance: models.Model, **kwargs: Any) -> None: if self.monitor in instance.get_deferred_fields(): # Fix related to issue #241 to avoid recursive error on double monitor fields return setattr(instance, self.monitor_attname, self.get_monitored_value(instance)) def pre_save(self, model_instance: models.Model, add: bool) -> Any: value = now() previous = getattr(model_instance, self.monitor_attname, None) current = self.get_monitored_value(model_instance) if previous != current: if self.when is None or current in self.when: setattr(model_instance, self.attname, value) self._save_initial(model_instance.__class__, model_instance) return super().pre_save(model_instance, add) def deconstruct(self) -> tuple[str, str, Sequence[Any], dict[str, Any]]: name, path, args, kwargs = super().deconstruct() kwargs['monitor'] = self.monitor if self.when is not None: kwargs['when'] = self.when return name, path, args, kwargs SPLIT_MARKER = getattr(settings, 'SPLIT_MARKER', '') # the number of paragraphs after which to split if no marker SPLIT_DEFAULT_PARAGRAPHS = getattr(settings, 'SPLIT_DEFAULT_PARAGRAPHS', 2) def _excerpt_field_name(name: str) -> str: return '_%s_excerpt' % name def get_excerpt(content: str) -> str: excerpt: list[str] = [] default_excerpt = [] paras_seen = 0 for line in content.splitlines(): if not line.strip(): paras_seen += 1 if paras_seen < SPLIT_DEFAULT_PARAGRAPHS: default_excerpt.append(line) if line.strip() == SPLIT_MARKER: return '\n'.join(excerpt) excerpt.append(line) return '\n'.join(default_excerpt) class SplitText: def __init__(self, instance: models.Model, field_name: str, excerpt_field_name: str): # instead of storing actual values store a reference to the instance # along with field names, this makes assignment possible self.instance = instance self.field_name = field_name self.excerpt_field_name = excerpt_field_name @property def content(self) -> str: return self.instance.__dict__[self.field_name] @content.setter def content(self, val: str) -> None: setattr(self.instance, self.field_name, val) @property def excerpt(self) -> str: return getattr(self.instance, self.excerpt_field_name) @property def has_more(self) -> bool: return self.excerpt.strip() != self.content.strip() def __str__(self) -> str: return self.content class SplitDescriptor: def __init__(self, field: SplitField): self.field = field self.excerpt_field_name = _excerpt_field_name(self.field.name) def __get__(self, instance: models.Model, owner: type[models.Model]) -> SplitText: if instance is None: raise AttributeError('Can only be accessed via an instance.') return SplitText(instance, self.field.name, self.excerpt_field_name) def __set__(self, obj: models.Model, value: SplitText | str) -> None: if isinstance(value, SplitText): obj.__dict__[self.field.name] = value.content setattr(obj, self.excerpt_field_name, value.excerpt) else: obj.__dict__[self.field.name] = value if TYPE_CHECKING: _SplitFieldBase = models.TextField[Union[SplitText, str], SplitText] else: _SplitFieldBase = models.TextField class SplitField(_SplitFieldBase): def contribute_to_class(self, cls: type[models.Model], name: str, *args: Any, **kwargs: Any) -> None: if not cls._meta.abstract: excerpt_field: models.TextField = models.TextField(editable=False) cls.add_to_class(_excerpt_field_name(name), excerpt_field) super().contribute_to_class(cls, name, *args, **kwargs) setattr(cls, self.name, SplitDescriptor(self)) def pre_save(self, model_instance: models.Model, add: bool) -> str: value: SplitText = super().pre_save(model_instance, add) excerpt = get_excerpt(value.content) setattr(model_instance, _excerpt_field_name(self.attname), excerpt) return value.content def value_to_string(self, obj: models.Model) -> str: value = self.value_from_object(obj) return value.content def get_prep_value(self, value: Any) -> str: try: return value.content except AttributeError: return value class UUIDField(models.UUIDField): """ A field for storing universally unique identifiers. Use Python UUID class. """ def __init__( self, primary_key: bool = True, version: int = 4, editable: bool = False, *args: Any, **kwargs: Any ): """ Parameters ---------- primary_key : bool If True, this field is the primary key for the model. version : int An integer that set default UUID version. editable : bool If False, the field will not be displayed in the admin or any other ModelForm, default is false. Raises ------ ValidationError UUID version 2 is not supported. """ if version == 2: raise ValidationError( 'UUID version 2 is not supported.') if version < 1 or version > 5: raise ValidationError( 'UUID version is not valid.') default: Callable[..., uuid.UUID] if version == 1: default = uuid.uuid1 elif version == 3: default = uuid.uuid3 elif version == 4: default = uuid.uuid4 elif version == 5: default = uuid.uuid5 kwargs.setdefault('primary_key', primary_key) kwargs.setdefault('editable', editable) kwargs.setdefault('default', default) super().__init__(*args, **kwargs) class UrlsafeTokenField(models.CharField): """ A field for storing a unique token in database. """ max_length: int def __init__( self, editable: bool = False, max_length: int = 128, factory: Callable[[int], str] | None = None, **kwargs: Any ): """ Parameters ---------- editable: bool If true token is editable. max_length: int Maximum length of the token. factory: callable If provided, called with max_length of the field instance to generate token. Raises ------ TypeError non-callable value for factory is not supported. """ if factory is not None and not callable(factory): raise TypeError("'factory' should either be a callable or 'None'") self._factory = factory kwargs.pop('default', None) # passing default value has not effect. super().__init__(editable=editable, max_length=max_length, **kwargs) def get_default(self) -> str: if self._factory is not None: return self._factory(self.max_length) # generate a token of length x1.33 approx. trim up to max length token = secrets.token_urlsafe(self.max_length)[:self.max_length] return token def deconstruct(self) -> tuple[str, str, Sequence[Any], dict[str, Any]]: name, path, args, kwargs = super().deconstruct() kwargs['factory'] = self._factory return name, path, args, kwargs jazzband-django-model-utils-aeef108/model_utils/locale/000077500000000000000000000000001466577571100233065ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/model_utils/locale/cs/000077500000000000000000000000001466577571100237135ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/model_utils/locale/cs/LC_MESSAGES/000077500000000000000000000000001466577571100255005ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/model_utils/locale/cs/LC_MESSAGES/django.mo000066400000000000000000000012331466577571100272760ustar00rootroot00000000000000T z epv  createdendmodifiedstartstatusstatus changedProject-Id-Version: django-model-utils Report-Msgid-Bugs-To: PO-Revision-Date: 2018-05-04 13:46+0200 Last-Translator: Václav Dohnal Language-Team: N/A Language: cs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2; X-Generator: Poedit 2.0.7 vytvořenokonecupravenozačátekstavzměna stavujazzband-django-model-utils-aeef108/model_utils/locale/cs/LC_MESSAGES/django.po000066400000000000000000000017571466577571100273140ustar00rootroot00000000000000# Czech translations of django-model-utils # # This file is distributed under the same license as the django-model-utils package. # # Translators: # ------------ # Václav Dohnal , 2018. # msgid "" msgstr "" "Project-Id-Version: django-model-utils\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2024-04-01 15:01+0200\n" "PO-Revision-Date: 2018-05-04 13:46+0200\n" "Last-Translator: Václav Dohnal \n" "Language-Team: N/A\n" "Language: cs\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;\n" "X-Generator: Poedit 2.0.7\n" #: models.py:24 msgid "created" msgstr "vytvořeno" #: models.py:25 msgid "modified" msgstr "upraveno" #: models.py:49 msgid "start" msgstr "začátek" #: models.py:50 msgid "end" msgstr "konec" #: models.py:65 msgid "status" msgstr "stav" #: models.py:66 msgid "status changed" msgstr "změna stavu" jazzband-django-model-utils-aeef108/model_utils/locale/de/000077500000000000000000000000001466577571100236765ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/model_utils/locale/de/LC_MESSAGES/000077500000000000000000000000001466577571100254635ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/model_utils/locale/de/LC_MESSAGES/django.mo000066400000000000000000000011501466577571100272570ustar00rootroot00000000000000T E09 >IPWcreatedendmodifiedstartstatusstatus changedProject-Id-Version: django-model-utils Report-Msgid-Bugs-To: PO-Revision-Date: 2015-07-01 10:12+0200 Last-Translator: Philipp Steinhardt Language-Team: Language: de MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=2; plural=(n != 1); erstelltEndebearbeitetBeginnStatusStatus geändertjazzband-django-model-utils-aeef108/model_utils/locale/de/LC_MESSAGES/django.po000066400000000000000000000017641466577571100272750ustar00rootroot00000000000000# This file is distributed under the same license as the django-model-utils package. # # Translators: # Philipp Steinhardt , 2015. msgid "" msgstr "" "Project-Id-Version: django-model-utils\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2024-04-01 15:01+0200\n" "PO-Revision-Date: 2015-07-01 10:12+0200\n" "Last-Translator: Philipp Steinhardt \n" "Language-Team: \n" "Language: de\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: models.py:24 msgid "created" msgstr "erstellt" #: models.py:25 msgid "modified" msgstr "bearbeitet" #: models.py:49 msgid "start" msgstr "Beginn" #: models.py:50 msgid "end" msgstr "Ende" #: models.py:65 msgid "status" msgstr "Status" #: models.py:66 msgid "status changed" msgstr "Status geändert" #~ msgid "active" #~ msgstr "aktiv" #~ msgid "deleted" #~ msgstr "gelöscht" #~ msgid "on hold" #~ msgstr "wartend" jazzband-django-model-utils-aeef108/model_utils/locale/es/000077500000000000000000000000001466577571100237155ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/model_utils/locale/es/LC_MESSAGES/000077500000000000000000000000001466577571100255025ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/model_utils/locale/es/LC_MESSAGES/django.mo000066400000000000000000000012031466577571100272750ustar00rootroot00000000000000T bMT Xcjqcreatedendmodifiedstartstatusstatus changedProject-Id-Version: django-model-utils Report-Msgid-Bugs-To: PO-Revision-Date: 2020-03-29 11:14+0100 Last-Translator: Enrique Matías Sánchez Language-Team: Language: es MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=2; plural=(n != 1); X-Generator: Lokalize 2.0 creadofinmodificadoinicioestadoestado modificadojazzband-django-model-utils-aeef108/model_utils/locale/es/LC_MESSAGES/django.po000066400000000000000000000016371466577571100273130ustar00rootroot00000000000000# This file is distributed under the same license as the django-model-utils package. # # Translators: # Enrique Matías Sánchez , 2020. msgid "" msgstr "" "Project-Id-Version: django-model-utils\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2024-04-01 15:01+0200\n" "PO-Revision-Date: 2020-03-29 11:14+0100\n" "Last-Translator: Enrique Matías Sánchez \n" "Language-Team: \n" "Language: es\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" "X-Generator: Lokalize 2.0\n" #: models.py:24 msgid "created" msgstr "creado" #: models.py:25 msgid "modified" msgstr "modificado" #: models.py:49 msgid "start" msgstr "inicio" #: models.py:50 msgid "end" msgstr "fin" #: models.py:65 msgid "status" msgstr "estado" #: models.py:66 msgid "status changed" msgstr "estado modificado" jazzband-django-model-utils-aeef108/model_utils/locale/fa/000077500000000000000000000000001466577571100236745ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/model_utils/locale/fa/LC_MESSAGES/000077500000000000000000000000001466577571100254615ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/model_utils/locale/fa/LC_MESSAGES/django.mo000066400000000000000000000012101466577571100272520ustar00rootroot00000000000000T A, <GW `kcreatedendmodifiedstartstatusstatus changedProject-Id-Version: PACKAGE VERSION Report-Msgid-Bugs-To: PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE Last-Translator: FULL NAME Language-Team: LANGUAGE Language: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=2; plural=(n > 1); ایجاد شدپایاناصلاح شدشروعوضعیتوضعیت تغییر کردjazzband-django-model-utils-aeef108/model_utils/locale/fa/LC_MESSAGES/django.po000066400000000000000000000016261466577571100272700ustar00rootroot00000000000000# This file is distributed under the same license as the django-model-utils package. # # Translators: # Hasan Ramezani , 2020. msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2024-04-01 15:01+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" #: models.py:24 msgid "created" msgstr "ایجاد شد" #: models.py:25 msgid "modified" msgstr "اصلاح شد" #: models.py:49 msgid "start" msgstr "شروع" #: models.py:50 msgid "end" msgstr "پایان" #: models.py:65 msgid "status" msgstr "وضعیت" #: models.py:66 msgid "status changed" msgstr "وضعیت تغییر کرد" jazzband-django-model-utils-aeef108/model_utils/locale/fr/000077500000000000000000000000001466577571100237155ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/model_utils/locale/fr/LC_MESSAGES/000077500000000000000000000000001466577571100255025ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/model_utils/locale/fr/LC_MESSAGES/django.mo000066400000000000000000000011531466577571100273010ustar00rootroot00000000000000T N9@DMT[createdendmodifiedstartstatusstatus changedProject-Id-Version: django-model-utils Report-Msgid-Bugs-To: PO-Revision-Date: 2021-01-11 11:45+0100 Last-Translator: Florian Alu Language-Team: Language: fr MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=2; plural=(n > 1); X-Generator: Poedit 2.4.2 crééfinmodifiédébutstatutstatut modifiéjazzband-django-model-utils-aeef108/model_utils/locale/fr/LC_MESSAGES/django.po000066400000000000000000000016631466577571100273120ustar00rootroot00000000000000# French translations of django-model-utils # # This file is distributed under the same license as the django-model-utils package. # # Translators: # ------------ # Florian Alu , 2021. # msgid "" msgstr "" "Project-Id-Version: django-model-utils\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2024-04-01 15:01+0200\n" "PO-Revision-Date: 2021-01-11 11:45+0100\n" "Last-Translator: Florian Alu \n" "Language-Team: \n" "Language: fr\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" "X-Generator: Poedit 2.4.2\n" #: models.py:24 msgid "created" msgstr "créé" #: models.py:25 msgid "modified" msgstr "modifié" #: models.py:49 msgid "start" msgstr "début" #: models.py:50 msgid "end" msgstr "fin" #: models.py:65 msgid "status" msgstr "statut" #: models.py:66 msgid "status changed" msgstr "statut modifié" jazzband-django-model-utils-aeef108/model_utils/locale/pt_BR/000077500000000000000000000000001466577571100243145ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/model_utils/locale/pt_BR/LC_MESSAGES/000077500000000000000000000000001466577571100261015ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/model_utils/locale/pt_BR/LC_MESSAGES/django.mo000066400000000000000000000012001466577571100276710ustar00rootroot00000000000000T ^IP T_gncreatedendmodifiedstartstatusstatus changedProject-Id-Version: django-model-utils Report-Msgid-Bugs-To: PO-Revision-Date: 2023-07-20 22:05-0300 Last-Translator: Guilherme Croceetti <24530683+gmcrocetti@users.noreply.github.com> Language-Team: Language: pt_BR MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=2; plural=(n > 1); criadofimmodificadoinícioestadoestado modificadojazzband-django-model-utils-aeef108/model_utils/locale/pt_BR/LC_MESSAGES/django.po000066400000000000000000000016661466577571100277140ustar00rootroot00000000000000# This file is distributed under the same license as the django-model-utils package. # # Translators: # Guilherme Martins Crocetti <24530683+gmcrocetti@users.noreply.github.com>, 2023. msgid "" msgstr "" "Project-Id-Version: django-model-utils\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2024-04-01 15:00+0200\n" "PO-Revision-Date: 2023-07-20 22:05-0300\n" "Last-Translator: Guilherme Croceetti <24530683+gmcrocetti@users.noreply." "github.com>\n" "Language-Team: \n" "Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" #: models.py:24 msgid "created" msgstr "criado" #: models.py:25 msgid "modified" msgstr "modificado" #: models.py:49 msgid "start" msgstr "início" #: models.py:50 msgid "end" msgstr "fim" #: models.py:65 msgid "status" msgstr "estado" #: models.py:66 msgid "status changed" msgstr "estado modificado" jazzband-django-model-utils-aeef108/model_utils/locale/ru/000077500000000000000000000000001466577571100237345ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/model_utils/locale/ru/LC_MESSAGES/000077500000000000000000000000001466577571100255215ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/model_utils/locale/ru/LC_MESSAGES/django.mo000066400000000000000000000014371466577571100273250ustar00rootroot00000000000000T    createdendmodifiedstartstatusstatus changedProject-Id-Version: django-model-utils Report-Msgid-Bugs-To: PO-Revision-Date: 2017-05-22 19:46+0300 Last-Translator: Arseny Sysolyatin Language-Team: Language: ru MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : n%10==0 || (n%10>=5 && n%10<=9) || (n%100>=11 && n%100<=14)? 2 : 3); созданоконецизмененоначалостатусстатус измененjazzband-django-model-utils-aeef108/model_utils/locale/ru/LC_MESSAGES/django.po000066400000000000000000000020761466577571100273300ustar00rootroot00000000000000# This file is distributed under the same license as the django-model-utils package. # # Translators: # Arseny Sysolyatin , 2017. msgid "" msgstr "" "Project-Id-Version: django-model-utils\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2024-04-01 15:01+0200\n" "PO-Revision-Date: 2017-05-22 19:46+0300\n" "Last-Translator: Arseny Sysolyatin \n" "Language-Team: \n" "Language: ru\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && " "n%10<=4 && (n%100<12 || n%100>14) ? 1 : n%10==0 || (n%10>=5 && n%10<=9) || " "(n%100>=11 && n%100<=14)? 2 : 3);\n" #: models.py:24 msgid "created" msgstr "создано" #: models.py:25 msgid "modified" msgstr "изменено" #: models.py:49 msgid "start" msgstr "начало" #: models.py:50 msgid "end" msgstr "конец" #: models.py:65 msgid "status" msgstr "статус" #: models.py:66 msgid "status changed" msgstr "статус изменен" jazzband-django-model-utils-aeef108/model_utils/locale/sv/000077500000000000000000000000001466577571100237365ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/model_utils/locale/sv/LC_MESSAGES/000077500000000000000000000000001466577571100255235ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/model_utils/locale/sv/LC_MESSAGES/django.mo000066400000000000000000000011351466577571100273220ustar00rootroot00000000000000T B-49AGNcreatedendmodifiedstartstatusstatus changedProject-Id-Version: PACKAGE VERSION Report-Msgid-Bugs-To: PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE Last-Translator: FULL NAME Language-Team: LANGUAGE Language: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=2; plural=(n != 1); skapadslutändradstartstatusstatus ändradjazzband-django-model-utils-aeef108/model_utils/locale/sv/LC_MESSAGES/django.po000066400000000000000000000017411466577571100273300ustar00rootroot00000000000000# This file is distributed under the same license as the django-model-utils package. # # Translators: # Tomas Walch , 2022. msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2024-04-01 15:01+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: models.py:24 msgid "created" msgstr "skapad" #: models.py:25 msgid "modified" msgstr "ändrad" #: models.py:49 msgid "start" msgstr "start" #: models.py:50 msgid "end" msgstr "slut" #: models.py:65 msgid "status" msgstr "status" #: models.py:66 msgid "status changed" msgstr "status ändrad" #~ msgid "active" #~ msgstr "aktiv" #~ msgid "deleted" #~ msgstr "borttagen" #~ msgid "on hold" #~ msgstr "väntande" jazzband-django-model-utils-aeef108/model_utils/locale/zh_Hans/000077500000000000000000000000001466577571100247005ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/model_utils/locale/zh_Hans/LC_MESSAGES/000077500000000000000000000000001466577571100264655ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/model_utils/locale/zh_Hans/LC_MESSAGES/django.mo000066400000000000000000000011601466577571100302620ustar00rootroot00000000000000T 7 " / < IV]createdendmodifiedstartstatusstatus changedProject-Id-Version: PACKAGE VERSION Report-Msgid-Bugs-To: PO-Revision-Date: 2018-10-23 15:26+0800 Last-Translator: Zach Cheung Language-Team: Language: zh_CN MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=1; plural=0; 创建时间结束时间修改时间开始时间状态状态修改时间jazzband-django-model-utils-aeef108/model_utils/locale/zh_Hans/LC_MESSAGES/django.po000066400000000000000000000015761466577571100303000ustar00rootroot00000000000000# This file is distributed under the same license as the django-model-utils package. # # Translators: # Zach Cheung , 2018. msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2024-04-01 15:01+0200\n" "PO-Revision-Date: 2018-10-23 15:26+0800\n" "Last-Translator: Zach Cheung \n" "Language-Team: \n" "Language: zh_CN\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=1; plural=0;\n" #: models.py:24 msgid "created" msgstr "创建时间" #: models.py:25 msgid "modified" msgstr "修改时间" #: models.py:49 msgid "start" msgstr "开始时间" #: models.py:50 msgid "end" msgstr "结束时间" #: models.py:65 msgid "status" msgstr "状态" #: models.py:66 msgid "status changed" msgstr "状态修改时间" jazzband-django-model-utils-aeef108/model_utils/managers.py000066400000000000000000000434071466577571100242260ustar00rootroot00000000000000from __future__ import annotations import warnings from typing import TYPE_CHECKING, Any, Generic, Sequence, TypeVar, cast, overload from django.core.exceptions import ObjectDoesNotExist from django.db import connection, models from django.db.models.constants import LOOKUP_SEP from django.db.models.fields.related import OneToOneField, OneToOneRel from django.db.models.query import ModelIterable, QuerySet from django.db.models.sql.datastructures import Join ModelT = TypeVar('ModelT', bound=models.Model, covariant=True) if TYPE_CHECKING: from collections.abc import Iterator from django.db.models.query import BaseIterable def _iter_inheritance_queryset(queryset: QuerySet[ModelT]) -> Iterator[ModelT]: iter: ModelIterable[ModelT] = ModelIterable(queryset) if hasattr(queryset, 'subclasses'): assert hasattr(queryset, '_get_sub_obj_recurse') extras = tuple(queryset.query.extra.keys()) # sort the subclass names longest first, # so with 'a' and 'a__b' it goes as deep as possible subclasses = sorted(queryset.subclasses, key=len, reverse=True) for obj in iter: sub_obj = None for s in subclasses: sub_obj = queryset._get_sub_obj_recurse(obj, s) if sub_obj: break if not sub_obj: sub_obj = obj if hasattr(queryset, '_annotated'): for k in queryset._annotated: setattr(sub_obj, k, getattr(obj, k)) for k in extras: setattr(sub_obj, k, getattr(obj, k)) yield sub_obj else: yield from iter if TYPE_CHECKING: class InheritanceIterable(ModelIterable[ModelT]): queryset: QuerySet[ModelT] def __init__(self, queryset: QuerySet[ModelT], *args: Any, **kwargs: Any): ... def __iter__(self) -> Iterator[ModelT]: ... else: class InheritanceIterable(ModelIterable): def __iter__(self): return _iter_inheritance_queryset(self.queryset) class InheritanceQuerySetMixin(Generic[ModelT]): model: type[ModelT] subclasses: Sequence[str] def __init__(self, *args: object, **kwargs: object): super().__init__(*args, **kwargs) self._iterable_class: type[BaseIterable[ModelT]] = InheritanceIterable def select_subclasses(self, *subclasses: str | type[models.Model]) -> InheritanceQuerySet[ModelT]: model: type[ModelT] = self.model calculated_subclasses = self._get_subclasses_recurse(model) # if none were passed in, we can just short circuit and select all if not subclasses: selected_subclasses = calculated_subclasses else: verified_subclasses: list[str] = [] for subclass in subclasses: # special case for passing in the same model as the queryset # is bound against. Rather than raise an error later, we know # we can allow this through. if subclass is model: continue if not isinstance(subclass, str): subclass = self._get_ancestors_path(subclass) if subclass in calculated_subclasses: verified_subclasses.append(subclass) else: raise ValueError( '{!r} is not in the discovered subclasses, tried: {}'.format( subclass, ', '.join(calculated_subclasses)) ) selected_subclasses = verified_subclasses new_qs = cast('InheritanceQuerySet[ModelT]', self) if selected_subclasses: new_qs = new_qs.select_related(*selected_subclasses) new_qs.subclasses = selected_subclasses return new_qs def _chain(self, **kwargs: object) -> InheritanceQuerySet[ModelT]: update = {} for name in ['subclasses', '_annotated']: if hasattr(self, name): update[name] = getattr(self, name) # django-stubs doesn't include this private API. chained = super()._chain(**kwargs) # type: ignore[misc] chained.__dict__.update(update) return chained def _clone(self) -> InheritanceQuerySet[ModelT]: # django-stubs doesn't include this private API. qs = super()._clone() # type: ignore[misc] for name in ['subclasses', '_annotated']: if hasattr(self, name): setattr(qs, name, getattr(self, name)) return qs def annotate(self, *args: Any, **kwargs: Any) -> InheritanceQuerySet[ModelT]: qset = cast(QuerySet[ModelT], super()).annotate(*args, **kwargs) qset._annotated = [a.default_alias for a in args] + list(kwargs.keys()) return qset def _get_subclasses_recurse(self, model: type[models.Model]) -> list[str]: """ Given a Model class, find all related objects, exploring children recursively, returning a `list` of strings representing the relations for select_related """ related_objects = [ f for f in model._meta.get_fields() if isinstance(f, OneToOneRel)] rels = [ rel for rel in related_objects if isinstance(rel.field, OneToOneField) and issubclass(rel.field.model, model) and model is not rel.field.model and rel.parent_link ] subclasses = [] for rel in rels: for subclass in self._get_subclasses_recurse(rel.field.model): subclasses.append(rel.get_accessor_name() + LOOKUP_SEP + subclass) subclasses.append(rel.get_accessor_name()) return subclasses def _get_ancestors_path(self, model: type[models.Model]) -> str: """ Serves as an opposite to _get_subclasses_recurse, instead walking from the Model class up the Model's ancestry and constructing the desired select_related string backwards. """ if not issubclass(model, self.model): raise ValueError( f"{model!r} is not a subclass of {self.model!r}") ancestry: list[str] = [] # should be a OneToOneField or None parent_link = model._meta.get_ancestor_link(self.model) while parent_link is not None: related = parent_link.remote_field ancestry.insert(0, related.get_accessor_name()) parent_model = related.model parent_link = parent_model._meta.get_ancestor_link(self.model) return LOOKUP_SEP.join(ancestry) def _get_sub_obj_recurse(self, obj: models.Model, s: str) -> ModelT | None: rel, _, s = s.partition(LOOKUP_SEP) try: node = getattr(obj, rel) except ObjectDoesNotExist: return None if s: child = self._get_sub_obj_recurse(node, s) return child else: return node def get_subclass(self, *args: object, **kwargs: object) -> ModelT: return self.select_subclasses().get(*args, **kwargs) # Defining the 'model' attribute using a generic type triggers a bug in mypy: # https://github.com/python/mypy/issues/9031 class InheritanceQuerySet(InheritanceQuerySetMixin[ModelT], QuerySet[ModelT]): # type: ignore[misc] def instance_of(self, *models: type[ModelT]) -> InheritanceQuerySet[ModelT]: """ Fetch only objects that are instances of the provided model(s). """ # If we aren't already selecting the subclasses, we need # to in order to get this to work. # How can we tell if we are not selecting subclasses? # Is it safe to just apply .select_subclasses(*models)? # Due to https://code.djangoproject.com/ticket/16572, we # can't really do this for anything other than children (ie, # no grandchildren+). where_queries = [] for model in models: where_queries.append('(' + ' AND '.join([ '"{}"."{}" IS NOT NULL'.format( model._meta.db_table, field.column, ) for field in model._meta.parents.values() ]) + ')') return cast( 'InheritanceQuerySet[ModelT]', self.select_subclasses(*models).extra(where=[' OR '.join(where_queries)]) ) class InheritanceManagerMixin(Generic[ModelT]): _queryset_class = InheritanceQuerySet if TYPE_CHECKING: from collections.abc import Sequence def none(self) -> InheritanceQuerySet[ModelT]: ... def all(self) -> InheritanceQuerySet[ModelT]: ... def filter(self, *args: Any, **kwargs: Any) -> InheritanceQuerySet[ModelT]: ... def exclude(self, *args: Any, **kwargs: Any) -> InheritanceQuerySet[ModelT]: ... def complex_filter(self, filter_obj: Any) -> InheritanceQuerySet[ModelT]: ... def union(self, *other_qs: Any, all: bool = ...) -> InheritanceQuerySet[ModelT]: ... def intersection(self, *other_qs: Any) -> InheritanceQuerySet[ModelT]: ... def difference(self, *other_qs: Any) -> InheritanceQuerySet[ModelT]: ... def select_for_update( self, nowait: bool = ..., skip_locked: bool = ..., of: Sequence[str] = ..., no_key: bool = ... ) -> InheritanceQuerySet[ModelT]: ... def select_related(self, *fields: Any) -> InheritanceQuerySet[ModelT]: ... def prefetch_related(self, *lookups: Any) -> InheritanceQuerySet[ModelT]: ... def annotate(self, *args: Any, **kwargs: Any) -> InheritanceQuerySet[ModelT]: ... def alias(self, *args: Any, **kwargs: Any) -> InheritanceQuerySet[ModelT]: ... def order_by(self, *field_names: Any) -> InheritanceQuerySet[ModelT]: ... def distinct(self, *field_names: Any) -> InheritanceQuerySet[ModelT]: ... def extra( self, select: dict[str, Any] | None = ..., where: list[str] | None = ..., params: list[Any] | None = ..., tables: list[str] | None = ..., order_by: Sequence[str] | None = ..., select_params: Sequence[Any] | None = ..., ) -> InheritanceQuerySet[Any]: ... def reverse(self) -> InheritanceQuerySet[ModelT]: ... def defer(self, *fields: Any) -> InheritanceQuerySet[ModelT]: ... def only(self, *fields: Any) -> InheritanceQuerySet[ModelT]: ... def using(self, alias: str | None) -> InheritanceQuerySet[ModelT]: ... def get_queryset(self) -> InheritanceQuerySet[ModelT]: model: type[ModelT] = self.model # type: ignore[attr-defined] return self._queryset_class(model) def select_subclasses( self, *subclasses: str | type[models.Model] ) -> InheritanceQuerySet[ModelT]: return self.get_queryset().select_subclasses(*subclasses) def get_subclass(self, *args: object, **kwargs: object) -> ModelT: return self.get_queryset().get_subclass(*args, **kwargs) def instance_of(self, *models: type[ModelT]) -> InheritanceQuerySet[ModelT]: return self.get_queryset().instance_of(*models) class InheritanceManager(InheritanceManagerMixin[ModelT], models.Manager[ModelT]): pass class QueryManagerMixin(Generic[ModelT]): @overload def __init__(self, *args: models.Q): ... @overload def __init__(self, **kwargs: object): ... def __init__(self, *args: models.Q, **kwargs: object): if args: self._q = args[0] else: self._q = models.Q(**kwargs) self._order_by: tuple[Any, ...] | None = None super().__init__() def order_by(self, *args: Any) -> QueryManager[ModelT]: self._order_by = args return cast('QueryManager[ModelT]', self) def get_queryset(self) -> QuerySet[ModelT]: qs = super().get_queryset() # type: ignore[misc] qs = qs.filter(self._q) if self._order_by is not None: return qs.order_by(*self._order_by) return qs class QueryManager(QueryManagerMixin[ModelT], models.Manager[ModelT]): # type: ignore[misc] pass class SoftDeletableQuerySetMixin(Generic[ModelT]): """ QuerySet for SoftDeletableModel. Instead of removing instance sets its ``is_removed`` field to True. """ def delete(self) -> tuple[int, dict[str, int]]: """ Soft delete objects from queryset (set their ``is_removed`` field to True) """ model: type[ModelT] = self.model # type: ignore[attr-defined] number_of_deleted_objects = cast(QuerySet[ModelT], self).update(is_removed=True) return number_of_deleted_objects, {model._meta.label: number_of_deleted_objects} class SoftDeletableQuerySet(SoftDeletableQuerySetMixin[ModelT], QuerySet[ModelT]): pass class SoftDeletableManagerMixin(Generic[ModelT]): """ Manager that limits the queryset by default to show only not removed instances of model. """ _queryset_class = SoftDeletableQuerySet _db: str | None def __init__( self, *args: object, _emit_deprecation_warnings: bool = False, **kwargs: object ): self.emit_deprecation_warnings = _emit_deprecation_warnings super().__init__(*args, **kwargs) def get_queryset(self) -> SoftDeletableQuerySet[ModelT]: """ Return queryset limited to not removed entries. """ model: type[ModelT] = self.model # type: ignore[attr-defined] if self.emit_deprecation_warnings: warning_message = ( "{0}.objects model manager will include soft-deleted objects in an " "upcoming release; please use {0}.available_objects to continue " "excluding soft-deleted objects. See " "https://django-model-utils.readthedocs.io/en/stable/models.html" "#softdeletablemodel for more information." ).format(model.__class__.__name__) warnings.warn(warning_message, DeprecationWarning) return self._queryset_class( model=model, using=self._db, **({'hints': self._hints} if hasattr(self, '_hints') else {}) ).filter(is_removed=False) class SoftDeletableManager(SoftDeletableManagerMixin[ModelT], models.Manager[ModelT]): pass class JoinQueryset(models.QuerySet[Any]): def join(self, qs: QuerySet[Any] | None = None) -> QuerySet[Any]: ''' Join one queryset together with another using a temporary table. If no queryset is used, it will use the current queryset and join that to itself. `Join` either uses the current queryset and effectively does a self-join to create a new limited queryset OR it uses a queryset given by the user. The model of a given queryset needs to contain a valid foreign key to the current queryset to perform a join. A new queryset is then created. ''' to_field = 'id' if qs: fks = [ fk for fk in qs.model._meta.fields if getattr(fk, 'related_model', None) == self.model ] fk = fks[0] if fks else None model_set = f'{self.model.__name__.lower()}_set' key = fk or getattr(qs.model, model_set, None) if not key: raise ValueError('QuerySet is not related to current model') try: fk_column = key.column except AttributeError: fk_column = 'id' to_field = key.field.column qs = qs.only(fk_column) # if we give a qs we need to keep the model qs to not lose anything new_qs = self else: fk_column = 'id' qs = self.only(fk_column) new_qs = self.model._default_manager.all() TABLE_NAME = 'temp_stuff' query, params = qs.query.sql_with_params() sql = ''' DROP TABLE IF EXISTS {table_name}; DROP INDEX IF EXISTS {table_name}_id; CREATE TEMPORARY TABLE {table_name} AS {query}; CREATE INDEX {table_name}_{fk_column} ON {table_name} ({fk_column}); '''.format(table_name=TABLE_NAME, fk_column=fk_column, query=str(query)) with connection.cursor() as cursor: cursor.execute(sql, params) class TempModel(models.Model): temp_key = models.ForeignKey( self.model, on_delete=models.DO_NOTHING, db_column=fk_column, to_field=to_field ) class Meta: managed = False db_table = TABLE_NAME conn = Join( table_name=TempModel._meta.db_table, parent_alias=new_qs.query.get_initial_alias(), table_alias=None, join_type='INNER JOIN', join_field=self.model.tempmodel_set.rel, nullable=False ) new_qs.query.join(conn, reuse=None) return new_qs if not TYPE_CHECKING: # Hide deprecated API during type checking, to encourage switch to # 'JoinQueryset.as_manager()', which is supported by the mypy plugin # of django-stubs. class JoinManagerMixin: """ Manager that adds a method join. This method allows you to join two querysets together. """ def get_queryset(self): warnings.warn( "JoinManager and JoinManagerMixin are deprecated. " "Please use 'JoinQueryset.as_manager()' instead.", DeprecationWarning ) return self._queryset_class(model=self.model, using=self._db) class JoinManager(JoinManagerMixin): pass jazzband-django-model-utils-aeef108/model_utils/models.py000066400000000000000000000141071466577571100237070ustar00rootroot00000000000000from __future__ import annotations from typing import Any, Literal, TypeVar, overload from django.core.exceptions import ImproperlyConfigured from django.db import models from django.db.models.functions import Now from django.utils.translation import gettext_lazy as _ from model_utils.fields import ( AutoCreatedField, AutoLastModifiedField, MonitorField, StatusField, UUIDField, ) from model_utils.managers import QueryManager, SoftDeletableManager ModelT = TypeVar('ModelT', bound=models.Model, covariant=True) now = Now() class TimeStampedModel(models.Model): """ An abstract base class model that provides self-updating ``created`` and ``modified`` fields. """ created = AutoCreatedField(_('created')) modified = AutoLastModifiedField(_('modified')) def save(self, *args: Any, **kwargs: Any) -> None: """ Overriding the save method in order to make sure that modified field is updated even if it is not given as a parameter to the update field argument. """ update_fields = kwargs.get('update_fields', None) if update_fields: kwargs['update_fields'] = set(update_fields).union({'modified'}) super().save(*args, **kwargs) class Meta: abstract = True class TimeFramedModel(models.Model): """ An abstract base class model that provides ``start`` and ``end`` fields to record a timeframe. """ start = models.DateTimeField(_('start'), null=True, blank=True) end = models.DateTimeField(_('end'), null=True, blank=True) class Meta: abstract = True class StatusModel(models.Model): """ An abstract base class model with a ``status`` field that automatically uses a ``STATUS`` class attribute of choices, a ``status_changed`` date-time field that records when ``status`` was last modified, and an automatically-added manager for each status that returns objects with that status only. """ status = StatusField(_('status')) status_changed = MonitorField(_('status changed'), monitor='status') def save(self, *args: Any, **kwargs: Any) -> None: """ Overriding the save method in order to make sure that status_changed field is updated even if it is not given as a parameter to the update field argument. """ update_fields = kwargs.get('update_fields', None) if update_fields and 'status' in update_fields: kwargs['update_fields'] = set(update_fields).union({'status_changed'}) super().save(*args, **kwargs) class Meta: abstract = True def add_status_query_managers(sender: type[models.Model], **kwargs: Any) -> None: """ Add a Querymanager for each status item dynamically. """ if not issubclass(sender, StatusModel): return default_manager = sender._meta.default_manager assert default_manager is not None for value, display in getattr(sender, 'STATUS', ()): if _field_exists(sender, value): raise ImproperlyConfigured( "StatusModel: Model '%s' has a field named '%s' which " "conflicts with a status of the same name." % (sender.__name__, value) ) sender.add_to_class(value, QueryManager(status=value)) sender._meta.default_manager_name = default_manager.name def add_timeframed_query_manager(sender: type[models.Model], **kwargs: Any) -> None: """ Add a QueryManager for a specific timeframe. """ if not issubclass(sender, TimeFramedModel): return if _field_exists(sender, 'timeframed'): raise ImproperlyConfigured( "Model '%s' has a field named 'timeframed' " "which conflicts with the TimeFramedModel manager." % sender.__name__ ) sender.add_to_class('timeframed', QueryManager( (models.Q(start__lte=now) | models.Q(start__isnull=True)) & (models.Q(end__gte=now) | models.Q(end__isnull=True)) )) models.signals.class_prepared.connect(add_status_query_managers) models.signals.class_prepared.connect(add_timeframed_query_manager) def _field_exists(model_class: type[models.Model], field_name: str) -> bool: return field_name in [f.attname for f in model_class._meta.local_fields] class SoftDeletableModel(models.Model): """ An abstract base class model with a ``is_removed`` field that marks entries that are not going to be used anymore, but are kept in db for any reason. Default manager returns only not-removed entries. """ is_removed = models.BooleanField(default=False) class Meta: abstract = True objects: models.Manager[SoftDeletableModel] = SoftDeletableManager(_emit_deprecation_warnings=True) available_objects: models.Manager[SoftDeletableModel] = SoftDeletableManager() all_objects = models.Manager() # Note that soft delete does not return anything, # which doesn't conform to Django's interface. # https://github.com/jazzband/django-model-utils/issues/541 @overload # type: ignore[override] def delete( self, using: Any = None, *args: Any, soft: Literal[True] = True, **kwargs: Any ) -> None: ... @overload def delete( self, using: Any = None, *args: Any, soft: Literal[False], **kwargs: Any ) -> tuple[int, dict[str, int]]: ... def delete( self, using: Any = None, *args: Any, soft: bool = True, **kwargs: Any ) -> tuple[int, dict[str, int]] | None: """ Soft delete object (set its ``is_removed`` field to True). Actually delete object if setting ``soft`` to False. """ if soft: self.is_removed = True self.save(using=using) return None else: return super().delete(using, *args, **kwargs) class UUIDModel(models.Model): """ This abstract base class provides id field on any model that inherits from it which will be the primary key. """ id = UUIDField( primary_key=True, version=4, editable=False, ) class Meta: abstract = True jazzband-django-model-utils-aeef108/model_utils/py.typed000066400000000000000000000000001466577571100235340ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/model_utils/tracker.py000066400000000000000000000407111466577571100240570ustar00rootroot00000000000000from __future__ import annotations from copy import deepcopy from functools import wraps from typing import ( TYPE_CHECKING, Any, Generic, Iterable, Protocol, TypeVar, cast, overload, ) from django.core.exceptions import FieldError from django.db import models from django.db.models.fields.files import FieldFile if TYPE_CHECKING: from collections.abc import Callable, Mapping from types import TracebackType class _AugmentedModel(models.Model): _instance_initialized: bool _deferred_fields: set[str] T = TypeVar("T") class Descriptor(Protocol[T]): def __get__(self, instance: object, owner: type[object]) -> T: ... def __set__(self, instance: object, value: T) -> None: ... class FullDescriptor(Descriptor[T]): def __delete__(self, instance: object) -> None: ... class LightStateFieldFile(FieldFile): """ FieldFile subclass with the only aim to remove the instance from the state. The change introduced in Django 3.1 on FieldFile subclasses results in pickling the whole instance for every field tracked. As this is done on the initialization of objects, a simple queryset evaluation on Django 3.1+ can make the app unusable, as CPU and memory usage gets easily multiplied by magnitudes. """ def __getstate__(self) -> dict[str, Any]: """ We don't need to deepcopy the instance, so nullify if provided. """ state = super().__getstate__() if 'instance' in state: state['instance'] = None return state def lightweight_deepcopy(value: T) -> T: """ Use our lightweight class to avoid copying the instance on a FieldFile deepcopy. """ if isinstance(value, FieldFile): value = cast(T, LightStateFieldFile( instance=value.instance, field=value.field, name=value.name, )) return deepcopy(value) class DescriptorWrapper(Generic[T]): def __init__(self, field_name: str, descriptor: Descriptor[T], tracker_attname: str): self.field_name = field_name self.descriptor = descriptor self.tracker_attname = tracker_attname @overload def __get__(self, instance: None, owner: type[models.Model]) -> DescriptorWrapper[T]: ... @overload def __get__(self, instance: models.Model, owner: type[models.Model]) -> T: ... def __get__(self, instance: models.Model | None, owner: type[models.Model]) -> DescriptorWrapper[T] | T: if instance is None: return self was_deferred = self.field_name in instance.get_deferred_fields() value = self.descriptor.__get__(instance, owner) if was_deferred: tracker_instance = getattr(instance, self.tracker_attname) tracker_instance.saved_data[self.field_name] = lightweight_deepcopy(value) return value def __set__(self, instance: models.Model, value: T) -> None: initialized = hasattr(instance, '_instance_initialized') was_deferred = self.field_name in instance.get_deferred_fields() # Sentinel attribute to detect whether we are already trying to # set the attribute higher up the stack. This prevents infinite # recursion when retrieving deferred values from the database. recursion_sentinel_attname = '_setting_' + self.field_name already_setting = hasattr(instance, recursion_sentinel_attname) if initialized and was_deferred and not already_setting: setattr(instance, recursion_sentinel_attname, True) try: # Retrieve the value to set the saved_data value. # This will undefer the field getattr(instance, self.field_name) finally: instance.__dict__.pop(recursion_sentinel_attname, None) if hasattr(self.descriptor, '__set__'): self.descriptor.__set__(instance, value) else: instance.__dict__[self.field_name] = value def __getattr__(self, attr: str) -> T: return getattr(self.descriptor, attr) @staticmethod def cls_for_descriptor(descriptor: Descriptor[T]) -> type[DescriptorWrapper[T]]: if hasattr(descriptor, '__delete__'): return FullDescriptorWrapper else: return DescriptorWrapper class FullDescriptorWrapper(DescriptorWrapper[T]): """ Wrapper for descriptors with all three descriptor methods. """ def __delete__(self, obj: models.Model) -> None: cast(FullDescriptor[T], self.descriptor).__delete__(obj) class FieldsContext: """ A context manager for tracking nested reset fields contexts. If tracked fields is mentioned in more than one FieldsContext, it's state is being reset on exiting last context that mentions that field. >>> with fields_context(obj.tracker, 'f1', state=state): ... with fields_context(obj.tracker, 'f1', 'f2', state=state): ... obj.do_something_useful() ... # f2 is reset after inner context exit ... obj.do_something_else() ... # f1 is reset after outer context exit >>> * Note that fields are counted by passing same state dict * FieldsContext is instantiated using FieldInstanceTracker (`obj.tracker`) * Different objects has own state stack """ def __init__( self, tracker: FieldInstanceTracker, *fields: str, state: dict[str, int] | None = None ): """ :param tracker: FieldInstanceTracker instance to be reset after context exit :param fields: a list of field names to be tracked in current context :param state: shared state dict used to count number of field occurrences in context stack. On context enter each field mentioned in `fields` has +1 in shared state, and on exit it receives -1. Fields that have zero after context exit are reset in tracker instance. """ if state is None: state = {} self.tracker = tracker self.fields = fields self.state = state def __enter__(self) -> FieldsContext: """ Increments tracked fields occurrences count in shared state. """ for f in self.fields: self.state.setdefault(f, 0) self.state[f] += 1 return self def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: """ Decrements tracked fields occurrences count in shared state. If any field has no more occurrences in shared state, this field is being reset by tracker. """ reset_fields = [] for f in self.fields: self.state[f] -= 1 if self.state[f] == 0: reset_fields.append(f) del self.state[f] if reset_fields: self.tracker.set_saved_fields(fields=reset_fields) class FieldInstanceTracker: def __init__(self, instance: models.Model, fields: Iterable[str], field_map: Mapping[str, str]): self.instance = cast('_AugmentedModel', instance) self.fields = fields self.field_map = field_map self.context = FieldsContext(self, *self.fields) def __enter__(self) -> FieldsContext: return self.context.__enter__() def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: return self.context.__exit__(exc_type, exc_val, exc_tb) def __call__(self, *fields: str) -> FieldsContext: return FieldsContext(self, *fields, state=self.context.state) @property def deferred_fields(self) -> set[str]: return self.instance.get_deferred_fields() def get_field_value(self, field: str) -> Any: return getattr(self.instance, self.field_map[field]) def set_saved_fields(self, fields: Iterable[str] | None = None) -> None: if not self.instance.pk: self.saved_data = {} elif fields is None: self.saved_data = self.current() else: self.saved_data.update(**self.current(fields=fields)) # preventing mutable fields side effects for field, field_value in self.saved_data.items(): self.saved_data[field] = lightweight_deepcopy(field_value) def current(self, fields: Iterable[str] | None = None) -> dict[str, Any]: """Returns dict of current values for all tracked fields""" if fields is None: deferred_fields = self.deferred_fields if deferred_fields: fields = [ field for field in self.fields if field not in deferred_fields ] else: fields = self.fields return {f: self.get_field_value(f) for f in fields} def has_changed(self, field: str) -> bool: """Returns ``True`` if field has changed from currently saved value""" if field in self.fields: # deferred fields haven't changed if field in self.deferred_fields and field not in self.instance.__dict__: return False prev: object = self.previous(field) curr: object = self.get_field_value(field) return prev != curr else: raise FieldError('field "%s" not tracked' % field) def previous(self, field: str) -> Any: """Returns currently saved value of given field""" # handle deferred fields that have not yet been loaded from the database if self.instance.pk and field in self.deferred_fields and field not in self.saved_data: # if the field has not been assigned locally, simply fetch and un-defer the value if field not in self.instance.__dict__: self.get_field_value(field) # if the field has been assigned locally, store the local value, fetch the database value, # store database value to saved_data, and restore the local value else: current_value = self.get_field_value(field) self.instance.refresh_from_db(fields=[field]) self.saved_data[field] = lightweight_deepcopy(self.get_field_value(field)) setattr(self.instance, self.field_map[field], current_value) return self.saved_data.get(field) def changed(self) -> dict[str, Any]: """Returns dict of fields that changed since save (with old values)""" return { field: self.previous(field) for field in self.fields if self.has_changed(field) } class FieldTracker: tracker_class = FieldInstanceTracker def __init__(self, fields: Iterable[str] | None = None): # finalize_class() will replace None; pretend it is never None. self.fields = cast(Iterable[str], fields) @overload def __call__( self, func: None = None, fields: Iterable[str] | None = None ) -> Callable[[Callable[..., T]], Callable[..., T]]: ... @overload def __call__( self, func: Callable[..., T], fields: Iterable[str] | None = None ) -> Callable[..., T]: ... def __call__( self, func: Callable[..., T] | None = None, fields: Iterable[str] | None = None ) -> Callable[[Callable[..., T]], Callable[..., T]] | Callable[..., T]: def decorator(f: Callable[..., T]) -> Callable[..., T]: @wraps(f) def inner(obj: models.Model, *args: object, **kwargs: object) -> T: tracker = getattr(obj, self.attname) field_list = tracker.fields if fields is None else fields with tracker(*field_list): return f(obj, *args, **kwargs) return inner if func is None: return decorator return decorator(func) def get_field_map(self, cls: type[models.Model]) -> dict[str, str]: """Returns dict mapping fields names to model attribute names""" field_map = {field: field for field in self.fields} all_fields = {f.name: f.attname for f in cls._meta.fields} field_map.update(**{k: v for (k, v) in all_fields.items() if k in field_map}) return field_map def contribute_to_class(self, cls: type[models.Model], name: str) -> None: self.name = name self.attname = '_%s' % name models.signals.class_prepared.connect(self.finalize_class, sender=cls) def finalize_class(self, sender: type[models.Model], **kwargs: object) -> None: if self.fields is None or TYPE_CHECKING: self.fields = (field.attname for field in sender._meta.fields) self.fields = set(self.fields) for field_name in self.fields: descriptor: models.Field[Any, Any] = getattr(sender, field_name) wrapper_cls = DescriptorWrapper.cls_for_descriptor(descriptor) wrapped_descriptor = wrapper_cls(field_name, descriptor, self.attname) setattr(sender, field_name, wrapped_descriptor) self.field_map = self.get_field_map(sender) self.patch_init(sender) self.model_class = sender setattr(sender, self.name, self) self.patch_save(sender) def initialize_tracker( self, sender: type[models.Model], instance: models.Model, **kwargs: object ) -> None: if not isinstance(instance, self.model_class): return # Only init instances of given model (including children) tracker = self.tracker_class(instance, self.fields, self.field_map) setattr(instance, self.attname, tracker) tracker.set_saved_fields() cast('_AugmentedModel', instance)._instance_initialized = True def patch_init(self, model: type[models.Model]) -> None: original = getattr(model, '__init__') @wraps(original) def inner(instance: models.Model, *args: Any, **kwargs: Any) -> None: original(instance, *args, **kwargs) self.initialize_tracker(model, instance) setattr(model, '__init__', inner) def patch_save(self, model: type[models.Model]) -> None: self._patch(model, 'save_base', 'update_fields') self._patch(model, 'refresh_from_db', 'fields') def _patch(self, model: type[models.Model], method: str, fields_kwarg: str) -> None: original = getattr(model, method) @wraps(original) def inner(instance: models.Model, *args: object, **kwargs: Any) -> object: update_fields: Iterable[str] | None = kwargs.get(fields_kwarg) if update_fields is None: fields = self.fields else: fields = ( field for field in update_fields if field in self.fields ) tracker = getattr(instance, self.attname) with tracker(*fields): return original(instance, *args, **kwargs) setattr(model, method, inner) @overload def __get__(self, instance: None, owner: type[models.Model]) -> FieldTracker: ... @overload def __get__(self, instance: models.Model, owner: type[models.Model]) -> FieldInstanceTracker: ... def __get__(self, instance: models.Model | None, owner: type[models.Model]) -> FieldTracker | FieldInstanceTracker: if instance is None: return self else: return getattr(instance, self.attname) class ModelInstanceTracker(FieldInstanceTracker): def has_changed(self, field: str) -> bool: """Returns ``True`` if field has changed from currently saved value""" if not self.instance.pk: return True elif field in self.saved_data: prev: object = self.previous(field) curr: object = self.get_field_value(field) return prev != curr else: raise FieldError('field "%s" not tracked' % field) def changed(self) -> dict[str, Any]: """Returns dict of fields that changed since save (with old values)""" if not self.instance.pk: return {} saved = self.saved_data.items() current = self.current() return {k: v for k, v in saved if v != current[k]} class ModelTracker(FieldTracker): tracker_class = ModelInstanceTracker def get_field_map(self, cls: type[models.Model]) -> dict[str, str]: return {field: field for field in self.fields} jazzband-django-model-utils-aeef108/mypy.ini000066400000000000000000000005511466577571100212270ustar00rootroot00000000000000[mypy] disallow_incomplete_defs=True disallow_untyped_defs=True implicit_reexport=False pretty=True show_error_codes=True strict_equality=True warn_redundant_casts=True warn_unreachable=True warn_unused_ignores=True mypy_path = $MYPY_CONFIG_FILE_DIR plugins = mypy_django_plugin.main [mypy.plugins.django-stubs] django_settings_module = "tests.settings" jazzband-django-model-utils-aeef108/requirements-mypy.txt000066400000000000000000000000571466577571100240110ustar00rootroot00000000000000mypy==1.10.0 django-stubs==5.0.2 pytest==7.4.3 jazzband-django-model-utils-aeef108/requirements-test.txt000066400000000000000000000001141466577571100237640ustar00rootroot00000000000000pytest==7.4.3 pytest-django==4.5.2 psycopg2-binary==2.9.9 pytest-cov==4.1.0 jazzband-django-model-utils-aeef108/requirements.txt000066400000000000000000000001241466577571100230100ustar00rootroot00000000000000# Dependencies for development of django-model-utils tox sphinx time-machine twine jazzband-django-model-utils-aeef108/setup.cfg000066400000000000000000000002641466577571100213520ustar00rootroot00000000000000[build_sphinx] source-dir = docs/ build-dir = docs/_build all_files = 1 [tool:pytest] django_find_project = false DJANGO_SETTINGS_MODULE = tests.settings [isort] profile = black jazzband-django-model-utils-aeef108/setup.py000066400000000000000000000037721466577571100212520ustar00rootroot00000000000000import os from setuptools import find_packages, setup def long_desc(root_path): FILES = ['README.rst', 'CHANGES.rst'] for filename in FILES: filepath = os.path.realpath(os.path.join(root_path, filename)) if os.path.isfile(filepath): with open(filepath) as f: yield f.read() HERE = os.path.abspath(os.path.dirname(__file__)) long_description = "\n\n".join(long_desc(HERE)) setup( name='django-model-utils', use_scm_version={"version_scheme": "post-release"}, setup_requires=["setuptools_scm"], license="BSD", description='Django model mixins and utilities', long_description=long_description, long_description_content_type='text/x-rst', author='Carl Meyer', author_email='carl@oddbird.net', maintainer='JazzBand', url='https://github.com/jazzband/django-model-utils', packages=find_packages(exclude=['tests*']), python_requires=">=3.8", install_requires=['Django>=3.2'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', 'Programming Language :: Python :: 3.12', 'Framework :: Django', 'Framework :: Django :: 3.2', 'Framework :: Django :: 4.0', 'Framework :: Django :: 4.1', 'Framework :: Django :: 4.2', 'Framework :: Django :: 5.0', 'Framework :: Django :: 5.1', ], zip_safe=False, package_data={ 'model_utils': [ 'locale/*/LC_MESSAGES/django.po', 'locale/*/LC_MESSAGES/django.mo', 'py.typed', ], }, ) jazzband-django-model-utils-aeef108/tests/000077500000000000000000000000001466577571100206715ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/tests/__init__.py000066400000000000000000000000001466577571100227700ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/tests/fields.py000066400000000000000000000020021466577571100225030ustar00rootroot00000000000000from __future__ import annotations from typing import Any from django.db import models from django.db.backends.base.base import BaseDatabaseWrapper def mutable_from_db(value: object) -> Any: if value == '': return None try: if isinstance(value, (str,)): return [int(i) for i in value.split(',')] except ValueError: pass return value def mutable_to_db(value: object) -> str: if value is None: return '' if isinstance(value, list): value = ','.join(str(i) for i in value) return str(value) class MutableField(models.TextField): def to_python(self, value: object) -> Any: return mutable_from_db(value) def from_db_value(self, value: object, expression: object, connection: BaseDatabaseWrapper) -> Any: return mutable_from_db(value) def get_db_prep_save(self, value: object, connection: BaseDatabaseWrapper) -> str: value = super().get_db_prep_save(value, connection) return mutable_to_db(value) jazzband-django-model-utils-aeef108/tests/models.py000066400000000000000000000310551466577571100225320ustar00rootroot00000000000000from __future__ import annotations from typing import Any, ClassVar, TypeVar, overload from django.db import models from django.db.models import Manager from django.db.models.query import QuerySet from django.db.models.query_utils import DeferredAttribute from django.utils.translation import gettext_lazy as _ from model_utils import Choices from model_utils.fields import MonitorField, SplitField, StatusField, UUIDField from model_utils.managers import ( InheritanceManager, JoinQueryset, QueryManager, SoftDeletableManager, SoftDeletableQuerySet, ) from model_utils.models import ( SoftDeletableModel, StatusModel, TimeFramedModel, TimeStampedModel, UUIDModel, ) from model_utils.tracker import FieldTracker, ModelTracker from tests.fields import MutableField ModelT = TypeVar('ModelT', bound=models.Model, covariant=True) class InheritanceManagerTestRelated(models.Model): pass class InheritanceManagerTestParent(models.Model): # FileField is just a handy descriptor-using field. Refs #6. non_related_field_using_descriptor = models.FileField(upload_to="test") related = models.ForeignKey( InheritanceManagerTestRelated, related_name="imtests", null=True, on_delete=models.CASCADE) normal_field = models.TextField() related_self = models.OneToOneField( "self", related_name="imtests_self", null=True, on_delete=models.CASCADE) objects: ClassVar[InheritanceManager[InheritanceManagerTestParent]] = InheritanceManager() def __str__(self) -> str: return "{}({})".format( self.__class__.__name__[len('InheritanceManagerTest'):], self.pk, ) class InheritanceManagerTestChild1(InheritanceManagerTestParent): non_related_field_using_descriptor_2 = models.FileField(upload_to="test") normal_field_2 = models.TextField() objects: ClassVar[InheritanceManager[InheritanceManagerTestParent]] = InheritanceManager() class InheritanceManagerTestGrandChild1(InheritanceManagerTestChild1): text_field = models.TextField() class InheritanceManagerTestGrandChild1_2(InheritanceManagerTestChild1): text_field = models.TextField() class InheritanceManagerTestChild2(InheritanceManagerTestParent): non_related_field_using_descriptor_2 = models.FileField(upload_to="test") normal_field_2 = models.TextField() class InheritanceManagerTestChild3(InheritanceManagerTestParent): parent_ptr = models.OneToOneField( InheritanceManagerTestParent, related_name='manual_onetoone', parent_link=True, on_delete=models.CASCADE) class InheritanceManagerTestChild3_1(InheritanceManagerTestParent): parent_ptr = models.OneToOneField( InheritanceManagerTestParent, db_column="custom_parent_ptr", parent_link=True, on_delete=models.CASCADE) class InheritanceManagerTestChild4(InheritanceManagerTestParent): other_onetoone = models.OneToOneField( InheritanceManagerTestParent, related_name='non_inheritance_relation', parent_link=False, on_delete=models.CASCADE) # The following is needed because of that Django bug: # https://code.djangoproject.com/ticket/29998 parent_ptr = models.OneToOneField( InheritanceManagerTestParent, related_name='child4_onetoone', parent_link=True, on_delete=models.CASCADE) class TimeStamp(TimeStampedModel): test_field = models.PositiveSmallIntegerField(default=0) class TimeFrame(TimeFramedModel): pass class TimeFrameManagerAdded(TimeFramedModel): pass class Monitored(models.Model): name = models.CharField(max_length=25) name_changed = MonitorField(monitor="name") name_changed_nullable = MonitorField(monitor="name", null=True) class MonitorWhen(models.Model): name = models.CharField(max_length=25) name_changed = MonitorField(monitor="name", when=["Jose", "Maria"]) class MonitorWhenEmpty(models.Model): name = models.CharField(max_length=25) name_changed = MonitorField(monitor="name", when=[]) class DoubleMonitored(models.Model): name = models.CharField(max_length=25) name_changed = MonitorField(monitor="name") name2 = models.CharField(max_length=25) name_changed2 = MonitorField(monitor="name2") class Status(StatusModel): STATUS: Choices[str] = Choices( ("active", _("active")), ("deleted", _("deleted")), ("on_hold", _("on hold")), ) class StatusPlainTuple(StatusModel): STATUS = ( ("active", _("active")), ("deleted", _("deleted")), ("on_hold", _("on hold")), ) class StatusManagerAdded(StatusModel): STATUS = ( ("active", _("active")), ("deleted", _("deleted")), ("on_hold", _("on hold")), ) class StatusCustomManager(Manager): pass class AbstractCustomManagerStatusModel(StatusModel): """An abstract status model with a custom manager.""" STATUS = Choices( ("first_choice", _("First choice")), ("second_choice", _("Second choice")), ) objects = StatusCustomManager() class Meta: abstract = True class CustomManagerStatusModel(AbstractCustomManagerStatusModel): """A concrete status model with a custom manager.""" title = models.CharField(max_length=50) class Post(models.Model): published = models.BooleanField(default=False) confirmed = models.BooleanField(default=False) order = models.IntegerField() objects = models.Manager() public: ClassVar[QueryManager[Post]] = QueryManager(published=True) public_confirmed: ClassVar[QueryManager[Post]] = QueryManager( models.Q(published=True) & models.Q(confirmed=True)) public_reversed: ClassVar[QueryManager[Post]] = QueryManager( published=True).order_by("-order") class Meta: ordering = ("order",) class Article(models.Model): title = models.CharField(max_length=50) body = SplitField() class SplitFieldAbstractParent(models.Model): content = SplitField() class Meta: abstract = True class AbstractTracked(models.Model): class Meta: abstract = True class Tracked(models.Model): name = models.CharField(max_length=20) number = models.IntegerField() mutable = MutableField(default=None) tracker = FieldTracker() def save(self, *args: Any, **kwargs: Any) -> None: """ No-op save() to ensure that FieldTracker.patch_save() works. """ super().save(*args, **kwargs) class TrackerTimeStamped(TimeStampedModel): name = models.CharField(max_length=20) number = models.IntegerField() mutable = MutableField(default=None) tracker = FieldTracker() def save(self, *args: Any, **kwargs: Any) -> None: """ Automatically add "modified" to update_fields.""" update_fields = kwargs.get('update_fields') if update_fields is not None: kwargs['update_fields'] = set(update_fields) | {'modified'} super().save(*args, **kwargs) class TrackedFK(models.Model): fk = models.ForeignKey('Tracked', on_delete=models.CASCADE) tracker = FieldTracker() custom_tracker = FieldTracker(fields=['fk_id']) custom_tracker_without_id = FieldTracker(fields=['fk']) class TrackedAbstract(AbstractTracked): name = models.CharField(max_length=20) number = models.IntegerField() mutable = MutableField(default=None) tracker = ModelTracker() class TrackedNotDefault(models.Model): name = models.CharField(max_length=20) number = models.IntegerField() name_tracker = FieldTracker(fields=['name']) class TrackedNonFieldAttr(models.Model): number = models.FloatField() @property def rounded(self) -> int | None: return round(self.number) if self.number is not None else None tracker = FieldTracker(fields=['rounded']) class TrackedMultiple(models.Model): name = models.CharField(max_length=20) number = models.IntegerField() name_tracker = FieldTracker(fields=['name']) number_tracker = FieldTracker(fields=['number']) class TrackedFileField(models.Model): some_file = models.FileField(upload_to='test_location') tracker = FieldTracker() class InheritedTracked(Tracked): name2 = models.CharField(max_length=20) class InheritedTrackedFK(TrackedFK): custom_tracker = FieldTracker(fields=['fk_id']) custom_tracker_without_id = FieldTracker(fields=['fk']) class ModelTracked(models.Model): name = models.CharField(max_length=20) number = models.IntegerField() mutable = MutableField(default=None) tracker = ModelTracker() class ModelTrackedFK(models.Model): fk = models.ForeignKey('ModelTracked', on_delete=models.CASCADE) tracker = ModelTracker() custom_tracker = ModelTracker(fields=['fk_id']) custom_tracker_without_id = ModelTracker(fields=['fk']) class ModelTrackedNotDefault(models.Model): name = models.CharField(max_length=20) number = models.IntegerField() name_tracker = ModelTracker(fields=['name']) class ModelTrackedMultiple(models.Model): name = models.CharField(max_length=20) number = models.IntegerField() name_tracker = ModelTracker(fields=['name']) number_tracker = ModelTracker(fields=['number']) class InheritedModelTracked(ModelTracked): name2 = models.CharField(max_length=20) class StatusFieldDefaultFilled(models.Model): STATUS = Choices((0, "no", "No"), (1, "yes", "Yes")) status = StatusField(default=STATUS.yes) class StatusFieldDefaultNotFilled(models.Model): STATUS = Choices((0, "no", "No"), (1, "yes", "Yes")) status = StatusField() class StatusFieldChoicesName(models.Model): NAMED_STATUS = Choices((0, "no", "No"), (1, "yes", "Yes")) status = StatusField(choices_name='NAMED_STATUS') class SoftDeletable(SoftDeletableModel): """ Test model with additional manager for full access to model instances. """ name = models.CharField(max_length=20) all_objects: ClassVar[Manager[SoftDeletable]] = models.Manager() class CustomSoftDeleteQuerySet(SoftDeletableQuerySet[ModelT]): def only_read(self) -> QuerySet[ModelT]: return self.filter(is_read=True) class CustomSoftDelete(SoftDeletableModel): is_read = models.BooleanField(default=False) available_objects = SoftDeletableManager.from_queryset(CustomSoftDeleteQuerySet)() class StringyDescriptor: """ Descriptor that returns a string version of the underlying integer value. """ def __init__(self, name: str): self.name = name @overload def __get__(self, obj: None, cls: type[models.Model] | None = None) -> StringyDescriptor: ... @overload def __get__(self, obj: models.Model, cls: type[models.Model]) -> str: ... def __get__(self, obj: models.Model | None, cls: type[models.Model] | None = None) -> StringyDescriptor | str: if obj is None: return self if self.name in obj.get_deferred_fields(): # This queries the database, and sets the value on the instance. assert cls is not None fields_map = {f.name: f for f in cls._meta.fields} field = fields_map[self.name] DeferredAttribute(field=field).__get__(obj, cls) return str(obj.__dict__[self.name]) def __set__(self, obj: object, value: str) -> None: obj.__dict__[self.name] = int(value) def __delete__(self, obj: object) -> None: del obj.__dict__[self.name] class CustomDescriptorField(models.IntegerField): def contribute_to_class(self, cls: type[models.Model], name: str, *args: Any, **kwargs: Any) -> None: super().contribute_to_class(cls, name, *args, **kwargs) setattr(cls, name, StringyDescriptor(name)) class ModelWithCustomDescriptor(models.Model): custom_field = CustomDescriptorField() tracked_custom_field = CustomDescriptorField() regular_field = models.IntegerField() tracked_regular_field = models.IntegerField() tracker = FieldTracker(fields=['tracked_custom_field', 'tracked_regular_field']) class BoxJoinModel(models.Model): name = models.CharField(max_length=32) objects = JoinQueryset.as_manager() class JoinItemForeignKey(models.Model): weight = models.IntegerField() belonging = models.ForeignKey( BoxJoinModel, null=True, on_delete=models.CASCADE ) objects = JoinQueryset.as_manager() class CustomUUIDModel(UUIDModel): pass class CustomNotPrimaryUUIDModel(models.Model): uuid = UUIDField(primary_key=False) class TimeStampWithStatusModel(TimeStampedModel, StatusModel): STATUS = Choices( ("active", _("active")), ("deleted", _("deleted")), ("on_hold", _("on hold")), ) test_field = models.PositiveSmallIntegerField(default=0) jazzband-django-model-utils-aeef108/tests/settings.py000066400000000000000000000015001466577571100230770ustar00rootroot00000000000000import os INSTALLED_APPS = ( 'model_utils', 'tests', ) if os.environ.get('SQLITE'): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', }, } else: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": os.environ.get("POSTGRES_DB", "modelutils"), "USER": os.environ.get("POSTGRES_USER", 'postgres'), "PASSWORD": os.environ.get("POSTGRES_PASSWORD", ""), "HOST": os.environ.get("POSTGRES_HOST", "localhost"), "PORT": os.environ.get("POSTGRES_PORT", "5432") }, } SECRET_KEY = 'dummy' CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' USE_TZ = True jazzband-django-model-utils-aeef108/tests/test_choices.py000066400000000000000000000241301466577571100237170ustar00rootroot00000000000000from __future__ import annotations from typing import TYPE_CHECKING, Generic, TypeVar import pytest from django.test import TestCase from model_utils import Choices T = TypeVar("T") class ChoicesTestsMixin(Generic[T]): STATUS: Choices[T] def test_getattr(self) -> None: assert self.STATUS.DRAFT == 'DRAFT' def test_len(self) -> None: assert len(self.STATUS) == 2 def test_repr(self) -> None: assert repr(self.STATUS) == "Choices" + repr(( ('DRAFT', 'DRAFT', 'DRAFT'), ('PUBLISHED', 'PUBLISHED', 'PUBLISHED'), )) def test_wrong_length_tuple(self) -> None: with pytest.raises(ValueError): Choices(('a',)) # type: ignore[arg-type] def test_deepcopy(self) -> None: import copy assert list(self.STATUS) == list(copy.deepcopy(self.STATUS)) def test_equality(self) -> None: assert self.STATUS == Choices('DRAFT', 'PUBLISHED') def test_inequality(self) -> None: assert self.STATUS != ['DRAFT', 'PUBLISHED'] assert self.STATUS != Choices('DRAFT') def test_composability(self) -> None: assert Choices('DRAFT') + Choices('PUBLISHED') == self.STATUS assert Choices('DRAFT') + ('PUBLISHED',) == self.STATUS assert ('DRAFT',) + Choices('PUBLISHED') == self.STATUS def test_option_groups(self) -> None: # Note: The implementation accepts any kind of sequence, but the type system can only # track per-index types for tuples. if TYPE_CHECKING: c = Choices(('group a', ['one', 'two']), ('group b', ('three',))) else: c = Choices(('group a', ['one', 'two']), ['group b', ('three',)]) assert list(c) == [ ('group a', [('one', 'one'), ('two', 'two')]), ('group b', [('three', 'three')]), ] class ChoicesTests(TestCase, ChoicesTestsMixin[str]): def setUp(self) -> None: self.STATUS = Choices('DRAFT', 'PUBLISHED') def test_indexing(self) -> None: self.assertEqual(self.STATUS['PUBLISHED'], 'PUBLISHED') def test_iteration(self) -> None: self.assertEqual(tuple(self.STATUS), (('DRAFT', 'DRAFT'), ('PUBLISHED', 'PUBLISHED'))) def test_reversed(self) -> None: self.assertEqual(tuple(reversed(self.STATUS)), (('PUBLISHED', 'PUBLISHED'), ('DRAFT', 'DRAFT'))) def test_contains_value(self) -> None: self.assertTrue('PUBLISHED' in self.STATUS) self.assertTrue('DRAFT' in self.STATUS) def test_doesnt_contain_value(self) -> None: self.assertFalse('UNPUBLISHED' in self.STATUS) class LabelChoicesTests(TestCase, ChoicesTestsMixin[str]): def setUp(self) -> None: self.STATUS = Choices( ('DRAFT', 'is draft'), ('PUBLISHED', 'is published'), 'DELETED', ) def test_iteration(self) -> None: self.assertEqual(tuple(self.STATUS), ( ('DRAFT', 'is draft'), ('PUBLISHED', 'is published'), ('DELETED', 'DELETED'), )) def test_reversed(self) -> None: self.assertEqual(tuple(reversed(self.STATUS)), ( ('DELETED', 'DELETED'), ('PUBLISHED', 'is published'), ('DRAFT', 'is draft'), )) def test_indexing(self) -> None: self.assertEqual(self.STATUS['PUBLISHED'], 'is published') def test_default(self) -> None: self.assertEqual(self.STATUS.DELETED, 'DELETED') def test_provided(self) -> None: self.assertEqual(self.STATUS.DRAFT, 'DRAFT') def test_len(self) -> None: self.assertEqual(len(self.STATUS), 3) def test_equality(self) -> None: self.assertEqual(self.STATUS, Choices( ('DRAFT', 'is draft'), ('PUBLISHED', 'is published'), 'DELETED', )) def test_inequality(self) -> None: self.assertNotEqual(self.STATUS, [ ('DRAFT', 'is draft'), ('PUBLISHED', 'is published'), 'DELETED' ]) self.assertNotEqual(self.STATUS, Choices('DRAFT')) def test_repr(self) -> None: self.assertEqual(repr(self.STATUS), "Choices" + repr(( ('DRAFT', 'DRAFT', 'is draft'), ('PUBLISHED', 'PUBLISHED', 'is published'), ('DELETED', 'DELETED', 'DELETED'), ))) def test_contains_value(self) -> None: self.assertTrue('PUBLISHED' in self.STATUS) self.assertTrue('DRAFT' in self.STATUS) # This should be True, because both the display value # and the internal representation are both DELETED. self.assertTrue('DELETED' in self.STATUS) def test_doesnt_contain_value(self) -> None: self.assertFalse('UNPUBLISHED' in self.STATUS) def test_doesnt_contain_display_value(self) -> None: self.assertFalse('is draft' in self.STATUS) def test_composability(self) -> None: self.assertEqual( Choices(('DRAFT', 'is draft',)) + Choices(('PUBLISHED', 'is published'), 'DELETED'), self.STATUS ) self.assertEqual( (('DRAFT', 'is draft',),) + Choices(('PUBLISHED', 'is published'), 'DELETED'), self.STATUS ) self.assertEqual( Choices(('DRAFT', 'is draft',)) + (('PUBLISHED', 'is published'), 'DELETED'), self.STATUS ) def test_option_groups(self) -> None: if TYPE_CHECKING: c = Choices[int]( ('group a', [(1, 'one'), (2, 'two')]), ('group b', ((3, 'three'),)) ) else: c = Choices( ('group a', [(1, 'one'), (2, 'two')]), ['group b', ((3, 'three'),)] ) self.assertEqual( list(c), [ ('group a', [(1, 'one'), (2, 'two')]), ('group b', [(3, 'three')]), ], ) class IdentifierChoicesTests(TestCase, ChoicesTestsMixin[int]): def setUp(self) -> None: self.STATUS = Choices( (0, 'DRAFT', 'is draft'), (1, 'PUBLISHED', 'is published'), (2, 'DELETED', 'is deleted')) def test_iteration(self) -> None: self.assertEqual(tuple(self.STATUS), ( (0, 'is draft'), (1, 'is published'), (2, 'is deleted'), )) def test_reversed(self) -> None: self.assertEqual(tuple(reversed(self.STATUS)), ( (2, 'is deleted'), (1, 'is published'), (0, 'is draft'), )) def test_indexing(self) -> None: self.assertEqual(self.STATUS[1], 'is published') def test_getattr(self) -> None: self.assertEqual(self.STATUS.DRAFT, 0) def test_len(self) -> None: self.assertEqual(len(self.STATUS), 3) def test_repr(self) -> None: self.assertEqual(repr(self.STATUS), "Choices" + repr(( (0, 'DRAFT', 'is draft'), (1, 'PUBLISHED', 'is published'), (2, 'DELETED', 'is deleted'), ))) def test_contains_value(self) -> None: self.assertTrue(0 in self.STATUS) self.assertTrue(1 in self.STATUS) self.assertTrue(2 in self.STATUS) def test_doesnt_contain_value(self) -> None: self.assertFalse(3 in self.STATUS) def test_doesnt_contain_display_value(self) -> None: self.assertFalse('is draft' in self.STATUS) # type: ignore[operator] def test_doesnt_contain_python_attr(self) -> None: self.assertFalse('PUBLISHED' in self.STATUS) # type: ignore[operator] def test_equality(self) -> None: self.assertEqual(self.STATUS, Choices( (0, 'DRAFT', 'is draft'), (1, 'PUBLISHED', 'is published'), (2, 'DELETED', 'is deleted') )) def test_inequality(self) -> None: self.assertNotEqual(self.STATUS, [ (0, 'DRAFT', 'is draft'), (1, 'PUBLISHED', 'is published'), (2, 'DELETED', 'is deleted') ]) self.assertNotEqual(self.STATUS, Choices('DRAFT')) def test_composability(self) -> None: self.assertEqual( Choices( (0, 'DRAFT', 'is draft'), (1, 'PUBLISHED', 'is published') ) + Choices( (2, 'DELETED', 'is deleted'), ), self.STATUS ) self.assertEqual( Choices( (0, 'DRAFT', 'is draft'), (1, 'PUBLISHED', 'is published') ) + ( (2, 'DELETED', 'is deleted'), ), self.STATUS ) self.assertEqual( ( (0, 'DRAFT', 'is draft'), (1, 'PUBLISHED', 'is published') ) + Choices( (2, 'DELETED', 'is deleted'), ), self.STATUS ) def test_option_groups(self) -> None: if TYPE_CHECKING: c = Choices[int]( ('group a', [(1, 'ONE', 'one'), (2, 'TWO', 'two')]), ('group b', ((3, 'THREE', 'three'),)) ) else: c = Choices( ('group a', [(1, 'ONE', 'one'), (2, 'TWO', 'two')]), ['group b', ((3, 'THREE', 'three'),)] ) self.assertEqual( list(c), [ ('group a', [(1, 'one'), (2, 'two')]), ('group b', [(3, 'three')]), ], ) class SubsetChoicesTest(TestCase): def setUp(self) -> None: self.choices = Choices[int]( (0, 'a', 'A'), (1, 'b', 'B'), ) def test_nonexistent_identifiers_raise(self) -> None: with self.assertRaises(ValueError): self.choices.subset('a', 'c') def test_solo_nonexistent_identifiers_raise(self) -> None: with self.assertRaises(ValueError): self.choices.subset('c') def test_empty_subset_passes(self) -> None: subset = self.choices.subset() self.assertEqual(subset, Choices()) def test_subset_returns_correct_subset(self) -> None: subset = self.choices.subset('a') self.assertEqual(subset, Choices((0, 'a', 'A'))) jazzband-django-model-utils-aeef108/tests/test_fields/000077500000000000000000000000001466577571100231765ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/tests/test_fields/__init__.py000066400000000000000000000000001466577571100252750ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/tests/test_fields/test_field_tracker.py000066400000000000000000001107721466577571100274150ustar00rootroot00000000000000from __future__ import annotations from typing import TYPE_CHECKING, Any from django.core.cache import cache from django.core.exceptions import FieldError from django.db import models from django.db.models.fields.files import FieldFile from django.test import TestCase from model_utils import FieldTracker from model_utils.tracker import DescriptorWrapper, FieldInstanceTracker from tests.models import ( InheritedModelTracked, InheritedTracked, InheritedTrackedFK, ModelTracked, ModelTrackedFK, ModelTrackedMultiple, ModelTrackedNotDefault, Tracked, TrackedAbstract, TrackedFileField, TrackedFK, TrackedMultiple, TrackedNonFieldAttr, TrackedNotDefault, TrackerTimeStamped, ) if TYPE_CHECKING: MixinBase = TestCase else: MixinBase = object class FieldTrackerMixin(MixinBase): tracker: FieldInstanceTracker instance: models.Model def assertHasChanged(self, *, tracker: FieldInstanceTracker | None = None, **kwargs: Any) -> None: if tracker is None: tracker = self.tracker for field, value in kwargs.items(): if value is None: with self.assertRaises(FieldError): tracker.has_changed(field) else: self.assertEqual(tracker.has_changed(field), value) def assertPrevious(self, *, tracker: FieldInstanceTracker | None = None, **kwargs: Any) -> None: if tracker is None: tracker = self.tracker for field, value in kwargs.items(): self.assertEqual(tracker.previous(field), value) def assertChanged(self, *, tracker: FieldInstanceTracker | None = None, **kwargs: Any) -> None: if tracker is None: tracker = self.tracker self.assertEqual(tracker.changed(), kwargs) def assertCurrent(self, *, tracker: FieldInstanceTracker | None = None, **kwargs: Any) -> None: if tracker is None: tracker = self.tracker self.assertEqual(tracker.current(), kwargs) def update_instance(self, **kwargs: Any) -> None: for field, value in kwargs.items(): setattr(self.instance, field, value) self.instance.save() class FieldTrackerCommonMixin(FieldTrackerMixin): instance: ( Tracked | TrackedNotDefault | TrackedMultiple | ModelTracked | ModelTrackedNotDefault | ModelTrackedMultiple | TrackedAbstract ) def test_pre_save_previous(self) -> None: self.assertPrevious(name=None, number=None) self.instance.name = 'new age' self.instance.number = 8 self.assertPrevious(name=None, number=None) class FieldTrackerTests(FieldTrackerCommonMixin, TestCase): tracked_class: type[Tracked | ModelTracked | TrackedAbstract] = Tracked instance: Tracked | ModelTracked | TrackedAbstract def setUp(self) -> None: self.instance = self.tracked_class() self.tracker = self.instance.tracker def test_descriptor(self) -> None: tracker = self.tracked_class.tracker self.assertTrue(isinstance(tracker, FieldTracker)) def test_pre_save_changed(self) -> None: self.assertChanged(name=None) self.instance.name = 'new age' self.assertChanged(name=None) self.instance.number = 8 self.assertChanged(name=None, number=None) self.instance.name = '' self.assertChanged(name=None, number=None) self.instance.mutable = [1, 2, 3] self.assertChanged(name=None, number=None, mutable=None) def test_pre_save_has_changed(self) -> None: self.assertHasChanged(name=True, number=False, mutable=False) self.instance.name = 'new age' self.assertHasChanged(name=True, number=False, mutable=False) self.instance.number = 7 self.assertHasChanged(name=True, number=True) self.instance.mutable = [1, 2, 3] self.assertHasChanged(name=True, number=True, mutable=True) def test_save_with_args(self) -> None: self.instance.number = 1 self.instance.save(False, False, None, None) self.assertChanged() def test_first_save(self) -> None: self.assertHasChanged(name=True, number=False, mutable=False) self.assertPrevious(name=None, number=None, mutable=None) self.assertCurrent(name='', number=None, id=None, mutable=None) self.assertChanged(name=None) self.instance.name = 'retro' self.instance.number = 4 self.instance.mutable = [1, 2, 3] self.assertHasChanged(name=True, number=True, mutable=True) self.assertPrevious(name=None, number=None, mutable=None) self.assertCurrent(name='retro', number=4, id=None, mutable=[1, 2, 3]) self.assertChanged(name=None, number=None, mutable=None) self.instance.save(update_fields=[]) self.assertHasChanged(name=True, number=True, mutable=True) self.assertPrevious(name=None, number=None, mutable=None) self.assertCurrent(name='retro', number=4, id=None, mutable=[1, 2, 3]) self.assertChanged(name=None, number=None, mutable=None) with self.assertRaises(ValueError): self.instance.save(update_fields=['number']) def test_post_save_has_changed(self) -> None: self.update_instance(name='retro', number=4, mutable=[1, 2, 3]) self.assertHasChanged(name=False, number=False, mutable=False) self.instance.name = 'new age' self.assertHasChanged(name=True, number=False) self.instance.number = 8 self.assertHasChanged(name=True, number=True) self.instance.mutable[1] = 4 self.assertHasChanged(name=True, number=True, mutable=True) self.instance.name = 'retro' self.assertHasChanged(name=False, number=True, mutable=True) def test_post_save_previous(self) -> None: self.update_instance(name='retro', number=4, mutable=[1, 2, 3]) self.instance.name = 'new age' self.assertPrevious(name='retro', number=4, mutable=[1, 2, 3]) self.instance.mutable[1] = 4 self.assertPrevious(name='retro', number=4, mutable=[1, 2, 3]) def test_post_save_changed(self) -> None: self.update_instance(name='retro', number=4, mutable=[1, 2, 3]) self.assertChanged() self.instance.name = 'new age' self.assertChanged(name='retro') self.instance.number = 8 self.assertChanged(name='retro', number=4) self.instance.name = 'retro' self.assertChanged(number=4) self.instance.mutable[1] = 4 self.assertChanged(number=4, mutable=[1, 2, 3]) self.instance.mutable = [1, 2, 3] self.assertChanged(number=4) def test_current(self) -> None: self.assertCurrent(id=None, name='', number=None, mutable=None) self.instance.name = 'new age' self.assertCurrent(id=None, name='new age', number=None, mutable=None) self.instance.number = 8 self.assertCurrent(id=None, name='new age', number=8, mutable=None) self.instance.mutable = [1, 2, 3] self.assertCurrent(id=None, name='new age', number=8, mutable=[1, 2, 3]) self.instance.mutable[1] = 4 self.assertCurrent(id=None, name='new age', number=8, mutable=[1, 4, 3]) self.instance.save() self.assertCurrent(id=self.instance.id, name='new age', number=8, mutable=[1, 4, 3]) def test_update_fields(self) -> None: self.update_instance(name='retro', number=4, mutable=[1, 2, 3]) self.assertChanged() self.instance.name = 'new age' self.instance.number = 8 self.instance.mutable = [4, 5, 6] self.assertChanged(name='retro', number=4, mutable=[1, 2, 3]) self.instance.save(update_fields=[]) self.assertChanged(name='retro', number=4, mutable=[1, 2, 3]) self.instance.save(update_fields=['name']) in_db = self.tracked_class.objects.get(id=self.instance.id) self.assertEqual(in_db.name, self.instance.name) self.assertNotEqual(in_db.number, self.instance.number) self.assertChanged(number=4, mutable=[1, 2, 3]) self.instance.save(update_fields=['number']) self.assertChanged(mutable=[1, 2, 3]) self.instance.save(update_fields=['mutable']) self.assertChanged() in_db = self.tracked_class.objects.get(id=self.instance.id) self.assertEqual(in_db.name, self.instance.name) self.assertEqual(in_db.number, self.instance.number) self.assertEqual(in_db.mutable, self.instance.mutable) def test_refresh_from_db(self) -> None: self.update_instance(name='retro', number=4, mutable=[1, 2, 3]) self.tracked_class.objects.filter(pk=self.instance.pk).update( name='new age', number=8, mutable=[3, 2, 1]) self.assertChanged() self.instance.name = 'like in db' self.instance.number = 8 self.instance.mutable = [3, 2, 1] self.assertChanged(name='retro', number=4, mutable=[1, 2, 3]) self.instance.refresh_from_db(fields=('name',)) self.assertChanged(number=4, mutable=[1, 2, 3]) self.instance.refresh_from_db(fields={'mutable'}) self.assertChanged(number=4) self.instance.refresh_from_db() self.assertChanged() def test_with_deferred(self) -> None: self.instance.name = 'new age' self.instance.number = 1 self.instance.save() item = self.tracked_class.objects.only('name').first() assert item is not None self.assertTrue(item.get_deferred_fields()) # has_changed() returns False for deferred fields, without un-deferring them. # Use an if because ModelTracked doesn't support has_changed() in this case. if self.tracked_class == Tracked: self.assertFalse(item.tracker.has_changed('number')) self.assertIsInstance(item.__class__.number, DescriptorWrapper) self.assertTrue('number' in item.get_deferred_fields()) # previous() un-defers field and returns value self.assertEqual(item.tracker.previous('number'), 1) self.assertNotIn('number', item.get_deferred_fields()) # examining a deferred field un-defers it item = self.tracked_class.objects.only('name').first() assert item is not None self.assertEqual(item.number, 1) self.assertTrue('number' not in item.get_deferred_fields()) self.assertEqual(item.tracker.previous('number'), 1) self.assertFalse(item.tracker.has_changed('number')) # has_changed() returns correct values after deferred field is examined self.assertFalse(item.tracker.has_changed('number')) item.number = 2 self.assertTrue(item.tracker.has_changed('number')) # previous() returns correct value after deferred field is examined self.assertEqual(item.tracker.previous('number'), 1) # assigning to a deferred field un-defers it # Use an if because ModelTracked doesn't handle this case. if self.tracked_class == Tracked: item = self.tracked_class.objects.only('name').first() assert item is not None item.number = 2 # previous() fetches correct value from database after deferred field is assigned self.assertEqual(item.tracker.previous('number'), 1) # database fetch of previous() value doesn't affect current value self.assertEqual(item.number, 2) # has_changed() returns correct values after deferred field is assigned self.assertTrue(item.tracker.has_changed('number')) item.number = 1 self.assertFalse(item.tracker.has_changed('number')) class FieldTrackerMultipleInstancesTests(TestCase): def test_with_deferred_fields_access_multiple(self) -> None: Tracked.objects.create(pk=1, name='foo', number=1) Tracked.objects.create(pk=2, name='bar', number=2) queryset = Tracked.objects.only('id') for instance in queryset: instance.name class FieldTrackedModelCustomTests(FieldTrackerCommonMixin, TestCase): tracked_class: type[TrackedNotDefault | ModelTrackedNotDefault] = TrackedNotDefault instance: TrackedNotDefault | ModelTrackedNotDefault def setUp(self) -> None: self.instance = self.tracked_class() self.tracker = self.instance.name_tracker def test_pre_save_changed(self) -> None: self.assertChanged(name=None) self.instance.name = 'new age' self.assertChanged(name=None) self.instance.number = 8 self.assertChanged(name=None) self.instance.name = '' self.assertChanged(name=None) def test_first_save(self) -> None: self.assertHasChanged(name=True, number=None) self.assertPrevious(name=None, number=None) self.assertCurrent(name='') self.assertChanged(name=None) self.instance.name = 'retro' self.instance.number = 4 self.assertHasChanged(name=True, number=None) self.assertPrevious(name=None, number=None) self.assertCurrent(name='retro') self.assertChanged(name=None) def test_pre_save_has_changed(self) -> None: self.assertHasChanged(name=True, number=None) self.instance.name = 'new age' self.assertHasChanged(name=True, number=None) self.instance.number = 7 self.assertHasChanged(name=True, number=None) def test_post_save_has_changed(self) -> None: self.update_instance(name='retro', number=4) self.assertHasChanged(name=False, number=None) self.instance.name = 'new age' self.assertHasChanged(name=True, number=None) self.instance.number = 8 self.assertHasChanged(name=True, number=None) self.instance.name = 'retro' self.assertHasChanged(name=False, number=None) def test_post_save_previous(self) -> None: self.update_instance(name='retro', number=4) self.instance.name = 'new age' self.assertPrevious(name='retro', number=None) def test_post_save_changed(self) -> None: self.update_instance(name='retro', number=4) self.assertChanged() self.instance.name = 'new age' self.assertChanged(name='retro') self.instance.number = 8 self.assertChanged(name='retro') self.instance.name = 'retro' self.assertChanged() def test_current(self) -> None: self.assertCurrent(name='') self.instance.name = 'new age' self.assertCurrent(name='new age') self.instance.number = 8 self.assertCurrent(name='new age') self.instance.save() self.assertCurrent(name='new age') def test_update_fields(self) -> None: self.update_instance(name='retro', number=4) self.assertChanged() self.instance.name = 'new age' self.instance.number = 8 self.instance.save(update_fields=['name', 'number']) self.assertChanged() class FieldTrackedModelAttributeTests(FieldTrackerMixin, TestCase): tracked_class = TrackedNonFieldAttr instance: TrackedNonFieldAttr def setUp(self) -> None: self.instance = self.tracked_class() self.tracker = self.instance.tracker def test_previous(self) -> None: self.assertPrevious(rounded=None) self.instance.number = 7.5 self.assertPrevious(rounded=None) self.instance.save() self.assertPrevious(rounded=8) self.instance.number = 7.2 self.assertPrevious(rounded=8) self.instance.save() self.assertPrevious(rounded=7) def test_has_changed(self) -> None: self.assertHasChanged(rounded=False) self.instance.number = 7.5 self.assertHasChanged(rounded=True) self.instance.save() self.assertHasChanged(rounded=False) self.instance.number = 7.2 self.assertHasChanged(rounded=True) self.instance.number = 7.8 self.assertHasChanged(rounded=False) def test_changed(self) -> None: self.assertChanged() self.instance.number = 7.5 self.assertPrevious(rounded=None) self.instance.save() self.assertPrevious() self.instance.number = 7.8 self.assertPrevious() self.instance.number = 7.2 self.assertPrevious(rounded=8) self.instance.save() self.assertPrevious() def test_current(self) -> None: self.assertCurrent(rounded=None) self.instance.number = 7.5 self.assertCurrent(rounded=8) self.instance.save() self.assertCurrent(rounded=8) class FieldTrackedModelMultiTests(FieldTrackerCommonMixin, TestCase): tracked_class: type[TrackedMultiple | ModelTrackedMultiple] = TrackedMultiple instance: TrackedMultiple | ModelTrackedMultiple def setUp(self) -> None: self.instance = self.tracked_class() self.trackers = [self.instance.name_tracker, self.instance.number_tracker] def test_pre_save_changed(self) -> None: self.tracker = self.instance.name_tracker self.assertChanged(name=None) self.instance.name = 'new age' self.assertChanged(name=None) self.instance.number = 8 self.assertChanged(name=None) self.instance.name = '' self.assertChanged(name=None) self.tracker = self.instance.number_tracker self.assertChanged(number=None) self.instance.name = 'new age' self.assertChanged(number=None) self.instance.number = 8 self.assertChanged(number=None) def test_pre_save_has_changed(self) -> None: self.tracker = self.instance.name_tracker self.assertHasChanged(name=True, number=None) self.instance.name = 'new age' self.assertHasChanged(name=True, number=None) self.tracker = self.instance.number_tracker self.assertHasChanged(name=None, number=False) self.instance.name = 'new age' self.assertHasChanged(name=None, number=False) def test_pre_save_previous(self) -> None: for tracker in self.trackers: self.tracker = tracker super().test_pre_save_previous() def test_post_save_has_changed(self) -> None: self.update_instance(name='retro', number=4) self.assertHasChanged(tracker=self.trackers[0], name=False, number=None) self.assertHasChanged(tracker=self.trackers[1], name=None, number=False) self.instance.name = 'new age' self.assertHasChanged(tracker=self.trackers[0], name=True, number=None) self.assertHasChanged(tracker=self.trackers[1], name=None, number=False) self.instance.number = 8 self.assertHasChanged(tracker=self.trackers[0], name=True, number=None) self.assertHasChanged(tracker=self.trackers[1], name=None, number=True) self.instance.name = 'retro' self.instance.number = 4 self.assertHasChanged(tracker=self.trackers[0], name=False, number=None) self.assertHasChanged(tracker=self.trackers[1], name=None, number=False) def test_post_save_previous(self) -> None: self.update_instance(name='retro', number=4) self.instance.name = 'new age' self.instance.number = 8 self.assertPrevious(tracker=self.trackers[0], name='retro', number=None) self.assertPrevious(tracker=self.trackers[1], name=None, number=4) def test_post_save_changed(self) -> None: self.update_instance(name='retro', number=4) self.assertChanged(tracker=self.trackers[0]) self.assertChanged(tracker=self.trackers[1]) self.instance.name = 'new age' self.assertChanged(tracker=self.trackers[0], name='retro') self.assertChanged(tracker=self.trackers[1]) self.instance.number = 8 self.assertChanged(tracker=self.trackers[0], name='retro') self.assertChanged(tracker=self.trackers[1], number=4) self.instance.name = 'retro' self.instance.number = 4 self.assertChanged(tracker=self.trackers[0]) self.assertChanged(tracker=self.trackers[1]) def test_current(self) -> None: self.assertCurrent(tracker=self.trackers[0], name='') self.assertCurrent(tracker=self.trackers[1], number=None) self.instance.name = 'new age' self.assertCurrent(tracker=self.trackers[0], name='new age') self.assertCurrent(tracker=self.trackers[1], number=None) self.instance.number = 8 self.assertCurrent(tracker=self.trackers[0], name='new age') self.assertCurrent(tracker=self.trackers[1], number=8) self.instance.save() self.assertCurrent(tracker=self.trackers[0], name='new age') self.assertCurrent(tracker=self.trackers[1], number=8) class FieldTrackerForeignKeyMixin(FieldTrackerMixin): fk_class: type[Tracked | ModelTracked] tracked_class: type[TrackedFK | ModelTrackedFK] instance: TrackedFK | ModelTrackedFK def setUp(self) -> None: self.old_fk = self.fk_class.objects.create(number=8) self.instance = self.tracked_class.objects.create(fk=self.old_fk) # type: ignore[misc] def test_default(self) -> None: self.tracker = self.instance.tracker self.assertChanged() self.assertPrevious() self.assertCurrent(id=self.instance.id, fk_id=self.old_fk.id) self.instance.fk = self.fk_class.objects.create(number=8) # type: ignore[assignment] self.assertChanged(fk_id=self.old_fk.id) self.assertPrevious(fk_id=self.old_fk.id) self.assertCurrent(id=self.instance.id, fk_id=self.instance.fk_id) def test_custom(self) -> None: self.tracker = self.instance.custom_tracker self.assertChanged() self.assertPrevious() self.assertCurrent(fk_id=self.old_fk.id) self.instance.fk = self.fk_class.objects.create(number=8) # type: ignore[assignment] self.assertChanged(fk_id=self.old_fk.id) self.assertPrevious(fk_id=self.old_fk.id) self.assertCurrent(fk_id=self.instance.fk_id) def test_custom_without_id(self) -> None: with self.assertNumQueries(1): self.tracked_class.objects.get() self.tracker = self.instance.custom_tracker_without_id self.assertChanged() self.assertPrevious() self.assertCurrent(fk=self.old_fk.id) self.instance.fk = self.fk_class.objects.create(number=8) # type: ignore[assignment] self.assertChanged(fk=self.old_fk.id) self.assertPrevious(fk=self.old_fk.id) self.assertCurrent(fk=self.instance.fk_id) class FieldTrackerForeignKeyTests(FieldTrackerForeignKeyMixin, TestCase): fk_class = Tracked tracked_class = TrackedFK class FieldTrackerForeignKeyPrefetchRelatedTests(FieldTrackerMixin, TestCase): """Test that using `prefetch_related` on a tracked field does not raise a ValueError.""" fk_class = Tracked tracked_class = TrackedFK instance: TrackedFK def setUp(self) -> None: model_tracked = self.fk_class.objects.create(name="", number=0) self.instance = self.tracked_class.objects.create(fk=model_tracked) def test_default(self) -> None: self.tracker = self.instance.tracker self.assertIsNotNone(list(self.tracked_class.objects.prefetch_related("fk"))) def test_custom(self) -> None: self.tracker = self.instance.custom_tracker self.assertIsNotNone(list(self.tracked_class.objects.prefetch_related("fk"))) def test_custom_without_id(self) -> None: self.tracker = self.instance.custom_tracker_without_id self.assertIsNotNone(list(self.tracked_class.objects.prefetch_related("fk"))) class FieldTrackerTimeStampedTests(FieldTrackerMixin, TestCase): fk_class = Tracked tracked_class = TrackerTimeStamped instance: TrackerTimeStamped def setUp(self) -> None: self.instance = self.tracked_class.objects.create(name='old', number=1) self.tracker = self.instance.tracker def test_set_modified_on_save(self) -> None: old_modified = self.instance.modified self.instance.name = 'new' self.instance.save() self.assertGreater(self.instance.modified, old_modified) self.assertChanged() def test_set_modified_on_save_update_fields(self) -> None: old_modified = self.instance.modified self.instance.name = 'new' self.instance.save(update_fields=('name',)) self.assertGreater(self.instance.modified, old_modified) self.assertChanged() class InheritedFieldTrackerTests(FieldTrackerTests): tracked_class = InheritedTracked def test_child_fields_not_tracked(self) -> None: self.name2 = 'test' self.assertEqual(self.tracker.previous('name2'), None) self.assertRaises(FieldError, self.tracker.has_changed, 'name2') class FieldTrackerInheritedForeignKeyTests(FieldTrackerForeignKeyTests): tracked_class = InheritedTrackedFK class FieldTrackerFileFieldTests(FieldTrackerMixin, TestCase): tracked_class = TrackedFileField instance: TrackedFileField def setUp(self) -> None: self.instance = self.tracked_class() self.tracker = self.instance.tracker self.some_file = 'something.txt' self.another_file = 'another.txt' def test_saved_data_without_instance(self) -> None: """ Tests that instance won't get copied by the Field Tracker. This change was introduced in Django 3.1 with https://github.com/django/django/pull/12055 It results in a dramatic CPU and memory usage of FieldTracker on FileField and its subclasses. The pickling/deepcopying the instance is useless in the context of FieldTracker thus we are skipping it. """ self.assertEqual(self.tracker.saved_data, {}) self.update_instance(some_file=self.some_file) field_file_copy = self.tracker.saved_data.get('some_file') assert field_file_copy is not None self.assertEqual(field_file_copy.__getstate__().get('instance'), None) self.assertEqual(self.instance.some_file.instance, self.instance) self.assertIsInstance(self.instance.some_file, FieldFile) def test_pre_save_changed(self) -> None: self.assertChanged(some_file=None) self.instance.some_file = self.some_file self.assertChanged(some_file=None) def test_pre_save_has_changed(self) -> None: self.assertHasChanged(some_file=True) self.instance.some_file = self.some_file self.assertHasChanged(some_file=True) def test_pre_save_previous(self) -> None: self.assertPrevious(some_file=None) self.instance.some_file = self.some_file self.assertPrevious(some_file=None) def test_post_save_changed(self) -> None: self.update_instance(some_file=self.some_file) self.assertChanged() previous_file = self.instance.some_file self.instance.some_file = self.another_file self.assertChanged(some_file=previous_file) # test deferred file field deferred_instance = self.tracked_class.objects.defer('some_file')[0] deferred_instance.some_file # access field to fetch from database self.assertChanged(tracker=deferred_instance.tracker) previous_file = deferred_instance.some_file deferred_instance.some_file = self.another_file self.assertChanged( tracker=deferred_instance.tracker, some_file=previous_file, ) def test_post_save_has_changed(self) -> None: self.update_instance(some_file=self.some_file) self.assertHasChanged(some_file=False) self.instance.some_file = self.another_file self.assertHasChanged(some_file=True) # test deferred file field deferred_instance = self.tracked_class.objects.defer('some_file')[0] deferred_instance.some_file # access field to fetch from database self.assertHasChanged( tracker=deferred_instance.tracker, some_file=False, ) deferred_instance.some_file = self.another_file self.assertHasChanged( tracker=deferred_instance.tracker, some_file=True, ) def test_post_save_previous(self) -> None: self.update_instance(some_file=self.some_file) previous_file = self.instance.some_file self.instance.some_file = self.another_file self.assertPrevious(some_file=previous_file) # test deferred file field deferred_instance = self.tracked_class.objects.defer('some_file')[0] deferred_instance.some_file # access field to fetch from database self.assertPrevious( tracker=deferred_instance.tracker, some_file=previous_file, ) deferred_instance.some_file = self.another_file self.assertPrevious( tracker=deferred_instance.tracker, some_file=previous_file, ) def test_current(self) -> None: self.assertCurrent(some_file=self.instance.some_file, id=None) self.instance.some_file = self.some_file self.assertCurrent(some_file=self.instance.some_file, id=None) # test deferred file field self.instance.save() deferred_instance = self.tracked_class.objects.defer('some_file')[0] deferred_instance.some_file # access field to fetch from database self.assertCurrent( some_file=self.instance.some_file, id=self.instance.id, ) self.instance.some_file = self.another_file self.assertCurrent( some_file=self.instance.some_file, id=self.instance.id, ) class ModelTrackerTests(FieldTrackerTests): tracked_class: type[ModelTracked | TrackedAbstract] = ModelTracked instance: ModelTracked def test_cache_compatible(self) -> None: cache.set('key', self.instance) instance = cache.get('key') instance.number = 1 instance.name = 'cached' instance.save() self.assertChanged() instance.number = 2 self.assertHasChanged(number=True) def test_pre_save_changed(self) -> None: self.assertChanged() self.instance.name = 'new age' self.assertChanged() self.instance.number = 8 self.assertChanged() self.instance.name = '' self.assertChanged() self.instance.mutable = [1, 2, 3] self.assertChanged() def test_first_save(self) -> None: self.assertHasChanged(name=True, number=True, mutable=True) self.assertPrevious(name=None, number=None, mutable=None) self.assertCurrent(name='', number=None, id=None, mutable=None) self.assertChanged() self.instance.name = 'retro' self.instance.number = 4 self.instance.mutable = [1, 2, 3] self.assertHasChanged(name=True, number=True, mutable=True) self.assertPrevious(name=None, number=None, mutable=None) self.assertCurrent(name='retro', number=4, id=None, mutable=[1, 2, 3]) self.assertChanged() self.instance.save(update_fields=[]) self.assertHasChanged(name=True, number=True, mutable=True) self.assertPrevious(name=None, number=None, mutable=None) self.assertCurrent(name='retro', number=4, id=None, mutable=[1, 2, 3]) self.assertChanged() with self.assertRaises(ValueError): self.instance.save(update_fields=['number']) def test_pre_save_has_changed(self) -> None: self.assertHasChanged(name=True, number=True) self.instance.name = 'new age' self.assertHasChanged(name=True, number=True) self.instance.number = 7 self.assertHasChanged(name=True, number=True) class ModelTrackedModelCustomTests(FieldTrackedModelCustomTests): tracked_class = ModelTrackedNotDefault def test_first_save(self) -> None: self.assertHasChanged(name=True, number=True) self.assertPrevious(name=None, number=None) self.assertCurrent(name='') self.assertChanged() self.instance.name = 'retro' self.instance.number = 4 self.assertHasChanged(name=True, number=True) self.assertPrevious(name=None, number=None) self.assertCurrent(name='retro') self.assertChanged() def test_pre_save_has_changed(self) -> None: self.assertHasChanged(name=True, number=True) self.instance.name = 'new age' self.assertHasChanged(name=True, number=True) self.instance.number = 7 self.assertHasChanged(name=True, number=True) def test_pre_save_changed(self) -> None: self.assertChanged() self.instance.name = 'new age' self.assertChanged() self.instance.number = 8 self.assertChanged() self.instance.name = '' self.assertChanged() class ModelTrackedModelMultiTests(FieldTrackedModelMultiTests): tracked_class = ModelTrackedMultiple def test_pre_save_has_changed(self) -> None: self.tracker = self.instance.name_tracker self.assertHasChanged(name=True, number=True) self.instance.name = 'new age' self.assertHasChanged(name=True, number=True) self.tracker = self.instance.number_tracker self.assertHasChanged(name=True, number=True) self.instance.name = 'new age' self.assertHasChanged(name=True, number=True) def test_pre_save_changed(self) -> None: self.tracker = self.instance.name_tracker self.assertChanged() self.instance.name = 'new age' self.assertChanged() self.instance.number = 8 self.assertChanged() self.instance.name = '' self.assertChanged() self.tracker = self.instance.number_tracker self.assertChanged() self.instance.name = 'new age' self.assertChanged() self.instance.number = 8 self.assertChanged() class ModelTrackerForeignKeyTests(FieldTrackerForeignKeyMixin, TestCase): fk_class = ModelTracked tracked_class = ModelTrackedFK instance: ModelTrackedFK def test_custom_without_id(self) -> None: with self.assertNumQueries(2): self.tracked_class.objects.get() self.tracker = self.instance.custom_tracker_without_id self.assertChanged() self.assertPrevious() self.assertCurrent(fk=self.old_fk) self.instance.fk = self.fk_class.objects.create(number=8) self.assertNotEqual(self.instance.fk, self.old_fk) self.assertChanged(fk=self.old_fk) self.assertPrevious(fk=self.old_fk) self.assertCurrent(fk=self.instance.fk) class InheritedModelTrackerTests(ModelTrackerTests): tracked_class = InheritedModelTracked def test_child_fields_not_tracked(self) -> None: self.name2 = 'test' self.assertEqual(self.tracker.previous('name2'), None) self.assertTrue(self.tracker.has_changed('name2')) class AbstractModelTrackerTests(ModelTrackerTests): tracked_class = TrackedAbstract class TrackerContextDecoratorTests(TestCase): def setUp(self) -> None: self.instance = Tracked.objects.create(number=1) self.tracker = self.instance.tracker def assertChanged(self, *fields: str) -> None: for f in fields: self.assertTrue(self.tracker.has_changed(f)) def assertNotChanged(self, *fields: str) -> None: for f in fields: self.assertFalse(self.tracker.has_changed(f)) def test_context_manager(self) -> None: with self.tracker: with self.tracker: self.instance.name = 'new' self.assertChanged('name') self.assertChanged('name') self.assertNotChanged('name') def test_context_manager_fields(self) -> None: with self.tracker('number'): with self.tracker('number', 'name'): self.instance.name = 'new' self.instance.number += 1 self.assertChanged('name', 'number') self.assertChanged('number') self.assertNotChanged('name') self.assertNotChanged('number', 'name') def test_tracker_decorator(self) -> None: @Tracked.tracker def tracked_method(obj: Tracked) -> None: obj.name = 'new' self.assertChanged('name') tracked_method(self.instance) self.assertNotChanged('name') def test_tracker_decorator_fields(self) -> None: @Tracked.tracker(fields=['name']) def tracked_method(obj: Tracked) -> None: obj.name = 'new' obj.number += 1 self.assertChanged('name', 'number') tracked_method(self.instance) self.assertChanged('number') self.assertNotChanged('name') def test_tracker_context_with_save(self) -> None: with self.tracker: self.instance.name = 'new' self.instance.save() self.assertChanged('name') self.assertNotChanged('name') jazzband-django-model-utils-aeef108/tests/test_fields/test_monitor_field.py000066400000000000000000000115511466577571100274440ustar00rootroot00000000000000from __future__ import annotations from datetime import datetime, timezone import time_machine from django.test import TestCase from model_utils.fields import MonitorField from tests.models import DoubleMonitored, Monitored, MonitorWhen, MonitorWhenEmpty class MonitorFieldTests(TestCase): def setUp(self) -> None: with time_machine.travel(datetime(2016, 1, 1, 10, 0, 0, tzinfo=timezone.utc)): self.instance = Monitored(name='Charlie') self.created = self.instance.name_changed def test_save_no_change(self) -> None: self.instance.save() self.assertEqual(self.instance.name_changed, self.created) def test_save_changed(self) -> None: with time_machine.travel(datetime(2016, 1, 1, 12, 0, 0, tzinfo=timezone.utc)): self.instance.name = 'Maria' self.instance.save() self.assertEqual(self.instance.name_changed, datetime(2016, 1, 1, 12, 0, 0, tzinfo=timezone.utc)) def test_double_save(self) -> None: self.instance.name = 'Jose' self.instance.save() changed = self.instance.name_changed self.instance.save() self.assertEqual(self.instance.name_changed, changed) def test_no_monitor_arg(self) -> None: with self.assertRaises(TypeError): MonitorField() # type: ignore[call-arg] def test_monitor_default_is_none_when_nullable(self) -> None: self.assertIsNone(self.instance.name_changed_nullable) expected_datetime = datetime(2022, 1, 18, 12, 0, 0, tzinfo=timezone.utc) self.instance.name = "Jose" with time_machine.travel(expected_datetime, tick=False): self.instance.save() self.assertEqual(self.instance.name_changed_nullable, expected_datetime) class MonitorWhenFieldTests(TestCase): """ Will record changes only when name is 'Jose' or 'Maria' """ def setUp(self) -> None: with time_machine.travel(datetime(2016, 1, 1, 10, 0, 0, tzinfo=timezone.utc)): self.instance = MonitorWhen(name='Charlie') self.created = self.instance.name_changed def test_save_no_change(self) -> None: self.instance.save() self.assertEqual(self.instance.name_changed, self.created) def test_save_changed_to_Jose(self) -> None: with time_machine.travel(datetime(2016, 1, 1, 12, 0, 0, tzinfo=timezone.utc)): self.instance.name = 'Jose' self.instance.save() self.assertEqual(self.instance.name_changed, datetime(2016, 1, 1, 12, 0, 0, tzinfo=timezone.utc)) def test_save_changed_to_Maria(self) -> None: with time_machine.travel(datetime(2016, 1, 1, 12, 0, 0, tzinfo=timezone.utc)): self.instance.name = 'Maria' self.instance.save() self.assertEqual(self.instance.name_changed, datetime(2016, 1, 1, 12, 0, 0, tzinfo=timezone.utc)) def test_save_changed_to_Pedro(self) -> None: self.instance.name = 'Pedro' self.instance.save() self.assertEqual(self.instance.name_changed, self.created) def test_double_save(self) -> None: self.instance.name = 'Jose' self.instance.save() changed = self.instance.name_changed self.instance.save() self.assertEqual(self.instance.name_changed, changed) class MonitorWhenEmptyFieldTests(TestCase): """ Monitor should never be updated id when is an empty list. """ def setUp(self) -> None: self.instance = MonitorWhenEmpty(name='Charlie') self.created = self.instance.name_changed def test_save_no_change(self) -> None: self.instance.save() self.assertEqual(self.instance.name_changed, self.created) def test_save_changed_to_Jose(self) -> None: self.instance.name = 'Jose' self.instance.save() self.assertEqual(self.instance.name_changed, self.created) def test_save_changed_to_Maria(self) -> None: self.instance.name = 'Maria' self.instance.save() self.assertEqual(self.instance.name_changed, self.created) class MonitorDoubleFieldTests(TestCase): def setUp(self) -> None: DoubleMonitored.objects.create(name='Charlie', name2='Charlie2') def test_recursion_error_with_only(self) -> None: # Any field passed to only() is generating a recursion error list(DoubleMonitored.objects.only('id')) def test_recursion_error_with_defer(self) -> None: # Only monitored fields passed to defer() are failing list(DoubleMonitored.objects.defer('name')) def test_monitor_still_works_with_deferred_fields_filtered_out_of_save_initial(self) -> None: obj = DoubleMonitored.objects.defer('name').get(name='Charlie') with time_machine.travel(datetime(2016, 12, 1, tzinfo=timezone.utc)): obj.name = 'Charlie2' obj.save() self.assertEqual(obj.name_changed, datetime(2016, 12, 1, tzinfo=timezone.utc)) jazzband-django-model-utils-aeef108/tests/test_fields/test_split_field.py000066400000000000000000000047321466577571100271130ustar00rootroot00000000000000from __future__ import annotations from django.test import TestCase from tests.models import Article, SplitFieldAbstractParent class SplitFieldTests(TestCase): full_text = 'summary\n\n\n\nmore' excerpt = 'summary\n' def setUp(self) -> None: self.post = Article.objects.create( title='example post', body=self.full_text) def test_unicode_content(self) -> None: self.assertEqual(str(self.post.body), self.full_text) def test_excerpt(self) -> None: self.assertEqual(self.post.body.excerpt, self.excerpt) def test_content(self) -> None: self.assertEqual(self.post.body.content, self.full_text) def test_has_more(self) -> None: self.assertTrue(self.post.body.has_more) def test_not_has_more(self) -> None: post = Article.objects.create(title='example 2', body='some text\n\nsome more\n') self.assertFalse(post.body.has_more) def test_load_back(self) -> None: post = Article.objects.get(pk=self.post.pk) self.assertEqual(post.body.content, self.post.body.content) self.assertEqual(post.body.excerpt, self.post.body.excerpt) def test_assign_to_body(self) -> None: new_text = 'different\n\n\n\nother' self.post.body = new_text self.post.save() self.assertEqual(str(self.post.body), new_text) def test_assign_to_content(self) -> None: new_text = 'different\n\n\n\nother' self.post.body.content = new_text self.post.save() self.assertEqual(str(self.post.body), new_text) def test_assign_to_excerpt(self) -> None: with self.assertRaises(AttributeError): self.post.body.excerpt = 'this should fail' # type: ignore[misc] def test_access_via_class(self) -> None: with self.assertRaises(AttributeError): Article.body def test_assign_splittext(self) -> None: a = Article(title='Some Title') a.body = self.post.body self.assertEqual(a.body.excerpt, 'summary\n') def test_value_to_string(self) -> None: f = self.post._meta.get_field('body') self.assertEqual(f.value_to_string(self.post), self.full_text) def test_abstract_inheritance(self) -> None: class Child(SplitFieldAbstractParent): pass self.assertEqual( [f.name for f in Child._meta.fields], ["id", "content", "_content_excerpt"]) jazzband-django-model-utils-aeef108/tests/test_fields/test_status_field.py000066400000000000000000000020531466577571100272750ustar00rootroot00000000000000from __future__ import annotations from django.test import TestCase from model_utils.fields import StatusField from tests.models import ( Article, StatusFieldChoicesName, StatusFieldDefaultFilled, StatusFieldDefaultNotFilled, ) class StatusFieldTests(TestCase): def test_status_with_default_filled(self) -> None: instance = StatusFieldDefaultFilled() self.assertEqual(instance.status, instance.STATUS.yes) def test_status_with_default_not_filled(self) -> None: instance = StatusFieldDefaultNotFilled() self.assertEqual(instance.status, instance.STATUS.no) def test_no_check_for_status(self) -> None: field = StatusField(no_check_for_status=True) # this model has no STATUS attribute, so checking for it would error field.prepare_class(Article) def test_get_status_display(self) -> None: instance = StatusFieldDefaultFilled() self.assertEqual(instance.get_status_display(), "Yes") def test_choices_name(self) -> None: StatusFieldChoicesName() jazzband-django-model-utils-aeef108/tests/test_fields/test_urlsafe_token_field.py000066400000000000000000000043551466577571100306220ustar00rootroot00000000000000from __future__ import annotations from unittest.mock import Mock from django.db.models import NOT_PROVIDED from django.test import TestCase from model_utils.fields import UrlsafeTokenField class UrlsaftTokenFieldTests(TestCase): def test_editable_default(self) -> None: field = UrlsafeTokenField() self.assertFalse(field.editable) def test_editable(self) -> None: field = UrlsafeTokenField(editable=True) self.assertTrue(field.editable) def test_max_length_default(self) -> None: field = UrlsafeTokenField() self.assertEqual(field.max_length, 128) def test_max_length(self) -> None: field = UrlsafeTokenField(max_length=256) self.assertEqual(field.max_length, 256) def test_factory_default(self) -> None: field = UrlsafeTokenField() self.assertIsNone(field._factory) def test_factory_not_callable(self) -> None: with self.assertRaises(TypeError): UrlsafeTokenField(factory='INVALID') # type: ignore[arg-type] def test_get_default(self) -> None: field = UrlsafeTokenField() value = field.get_default() self.assertEqual(len(value), field.max_length) def test_get_default_with_non_default_max_length(self) -> None: field = UrlsafeTokenField(max_length=64) value = field.get_default() self.assertEqual(len(value), 64) def test_get_default_with_factory(self) -> None: token = 'SAMPLE_TOKEN' factory = Mock(return_value=token) field = UrlsafeTokenField(factory=factory) value = field.get_default() self.assertEqual(value, token) factory.assert_called_once_with(field.max_length) def test_no_default_param(self) -> None: field = UrlsafeTokenField(default='DEFAULT') self.assertIs(field.default, NOT_PROVIDED) def test_deconstruct(self) -> None: def test_factory(max_length: int) -> str: assert False instance = UrlsafeTokenField(factory=test_factory) name, path, args, kwargs = instance.deconstruct() new_instance = UrlsafeTokenField(*args, **kwargs) self.assertIs(instance._factory, new_instance._factory) self.assertIs(test_factory, new_instance._factory) jazzband-django-model-utils-aeef108/tests/test_fields/test_uuid_field.py000066400000000000000000000023541466577571100267240ustar00rootroot00000000000000from __future__ import annotations import uuid from django.core.exceptions import ValidationError from django.test import TestCase from model_utils.fields import UUIDField class UUIDFieldTests(TestCase): def test_uuid_version_default(self) -> None: instance = UUIDField() self.assertEqual(instance.default, uuid.uuid4) def test_uuid_version_1(self) -> None: instance = UUIDField(version=1) self.assertEqual(instance.default, uuid.uuid1) def test_uuid_version_2_error(self) -> None: self.assertRaises(ValidationError, UUIDField, 'version', 2) def test_uuid_version_3(self) -> None: instance = UUIDField(version=3) self.assertEqual(instance.default, uuid.uuid3) def test_uuid_version_4(self) -> None: instance = UUIDField(version=4) self.assertEqual(instance.default, uuid.uuid4) def test_uuid_version_5(self) -> None: instance = UUIDField(version=5) self.assertEqual(instance.default, uuid.uuid5) def test_uuid_version_bellow_min(self) -> None: self.assertRaises(ValidationError, UUIDField, 'version', 0) def test_uuid_version_above_max(self) -> None: self.assertRaises(ValidationError, UUIDField, 'version', 6) jazzband-django-model-utils-aeef108/tests/test_inheritance_iterable.py000066400000000000000000000011071466577571100264410ustar00rootroot00000000000000from __future__ import annotations from django.db.models import Prefetch from django.test import TestCase from tests.models import InheritanceManagerTestChild1, InheritanceManagerTestParent class InheritanceIterableTest(TestCase): def test_prefetch(self) -> None: qs = InheritanceManagerTestChild1.objects.all().prefetch_related( Prefetch( 'normal_field', queryset=InheritanceManagerTestParent.objects.all(), to_attr='normal_field_prefetched' ) ) self.assertEqual(qs.count(), 0) jazzband-django-model-utils-aeef108/tests/test_managers/000077500000000000000000000000001466577571100235255ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/tests/test_managers/__init__.py000066400000000000000000000000001466577571100256240ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/tests/test_managers/test_inheritance_manager.py000066400000000000000000000564531466577571100311360ustar00rootroot00000000000000from __future__ import annotations from typing import TYPE_CHECKING from django.db import models from django.test import TestCase from model_utils.managers import InheritanceManager from tests.models import ( InheritanceManagerTestChild1, InheritanceManagerTestChild2, InheritanceManagerTestChild3, InheritanceManagerTestChild3_1, InheritanceManagerTestChild4, InheritanceManagerTestGrandChild1, InheritanceManagerTestGrandChild1_2, InheritanceManagerTestParent, InheritanceManagerTestRelated, TimeFrame, ) if TYPE_CHECKING: from django.db.models.fields.related_descriptors import RelatedManager class InheritanceManagerTests(TestCase): def setUp(self) -> None: self.child1 = InheritanceManagerTestChild1.objects.create() self.child2 = InheritanceManagerTestChild2.objects.create() self.grandchild1 = InheritanceManagerTestGrandChild1.objects.create() self.grandchild1_2 = \ InheritanceManagerTestGrandChild1_2.objects.create() def get_manager(self) -> InheritanceManager[InheritanceManagerTestParent]: return InheritanceManagerTestParent.objects def test_normal(self) -> None: children = { InheritanceManagerTestParent(pk=self.child1.pk), InheritanceManagerTestParent(pk=self.child2.pk), InheritanceManagerTestParent(pk=self.grandchild1.pk), InheritanceManagerTestParent(pk=self.grandchild1_2.pk), } self.assertEqual(set(self.get_manager().all()), children) def test_select_all_subclasses(self) -> None: children = {self.child1, self.child2} children.add(self.grandchild1) children.add(self.grandchild1_2) self.assertEqual( set(self.get_manager().select_subclasses()), children) def test_select_subclasses_invalid_relation(self) -> None: """ If an invalid relation string is provided, we can provide the user with a list which is valid, rather than just have the select_related() raise an AttributeError further in. """ regex = '^.+? is not in the discovered subclasses, tried:.+$' with self.assertRaisesRegex(ValueError, regex): self.get_manager().select_subclasses('user') def test_select_specific_subclasses(self) -> None: children = { self.child1, InheritanceManagerTestParent(pk=self.child2.pk), InheritanceManagerTestChild1(pk=self.grandchild1.pk), InheritanceManagerTestChild1(pk=self.grandchild1_2.pk), } self.assertEqual( set( self.get_manager().select_subclasses( "inheritancemanagertestchild1") ), children, ) def test_select_specific_grandchildren(self) -> None: children = { InheritanceManagerTestParent(pk=self.child1.pk), InheritanceManagerTestParent(pk=self.child2.pk), self.grandchild1, InheritanceManagerTestParent(pk=self.grandchild1_2.pk), } self.assertEqual( set( self.get_manager().select_subclasses( "inheritancemanagertestchild1__inheritancemanagertestgrandchild1" ) ), children, ) def test_children_and_grandchildren(self) -> None: children = { self.child1, InheritanceManagerTestParent(pk=self.child2.pk), self.grandchild1, InheritanceManagerTestChild1(pk=self.grandchild1_2.pk), } self.assertEqual( set( self.get_manager().select_subclasses( "inheritancemanagertestchild1", "inheritancemanagertestchild1__inheritancemanagertestgrandchild1" ) ), children, ) def test_get_subclass(self) -> None: self.assertEqual( self.get_manager().get_subclass(pk=self.child1.pk), self.child1) def test_get_subclass_on_queryset(self) -> None: self.assertEqual( self.get_manager().all().get_subclass(pk=self.child1.pk), self.child1) def test_prior_select_related(self) -> None: with self.assertNumQueries(1): obj = self.get_manager().select_related( "inheritancemanagertestchild1").select_subclasses( "inheritancemanagertestchild2").get(pk=self.child1.pk) obj.inheritancemanagertestchild1 def test_manually_specifying_parent_fk_including_grandchildren(self) -> None: """ given a Model which inherits from another Model, but also declares the OneToOne link manually using `related_name` and `parent_link`, ensure that the relation names and subclasses are obtained correctly. """ child3 = InheritanceManagerTestChild3.objects.create() qs = InheritanceManagerTestParent.objects.all() results = qs.select_subclasses().order_by('pk') expected_objs = [ self.child1, self.child2, self.grandchild1, self.grandchild1_2, child3 ] self.assertEqual(list(results), expected_objs) expected_related_names = [ 'inheritancemanagertestchild1__inheritancemanagertestgrandchild1', 'inheritancemanagertestchild1__inheritancemanagertestgrandchild1_2', 'inheritancemanagertestchild1', 'inheritancemanagertestchild2', 'manual_onetoone', # this was set via parent_link & related_name 'inheritancemanagertestchild3_1', 'child4_onetoone', ] self.assertEqual(set(results.subclasses), set(expected_related_names)) def test_manually_specifying_parent_fk_single_subclass(self) -> None: """ Using a string related_name when the relation is manually defined instead of implicit should still work in the same way. """ related_name = 'manual_onetoone' child3 = InheritanceManagerTestChild3.objects.create() qs = InheritanceManagerTestParent.objects.all() results = qs.select_subclasses(related_name).order_by('pk') expected_objs = [InheritanceManagerTestParent(pk=self.child1.pk), InheritanceManagerTestParent(pk=self.child2.pk), InheritanceManagerTestParent(pk=self.grandchild1.pk), InheritanceManagerTestParent(pk=self.grandchild1_2.pk), child3] self.assertEqual(list(results), expected_objs) expected_related_names = [related_name] self.assertEqual(set(results.subclasses), set(expected_related_names)) def test_filter_on_values_queryset(self) -> None: queryset = InheritanceManagerTestChild1.objects.values('id').filter(pk=self.child1.pk) self.assertEqual(list(queryset), [{'id': self.child1.pk}]) def test_values_list_on_select_subclasses(self) -> None: """ Using `select_subclasses` in conjunction with `values_list()` raised an exception in `_get_sub_obj_recurse()` because the result of `values_list()` is either a `tuple` or primitive objects if `flat=True` is specified, because no type checking was done prior to fetching child nodes. """ # Querysets are cast to lists to force immediate evaluation. # No exceptions must be thrown. # No argument to select_subclasses objs_1 = list( self.get_manager() .select_subclasses() .values_list('id') ) # String argument to select_subclasses objs_2 = list( self.get_manager() .select_subclasses( "inheritancemanagertestchild2" ) .values_list('id') ) # String argument to select_subclasses objs_3 = list( self.get_manager() .select_subclasses( InheritanceManagerTestChild2 ).values_list('id') ) assert all(( isinstance(objs_1, list), isinstance(objs_2, list), isinstance(objs_3, list), )) assert objs_1 == objs_2 == objs_3 class InheritanceManagerUsingModelsTests(TestCase): def setUp(self) -> None: self.parent1 = InheritanceManagerTestParent.objects.create() self.child1 = InheritanceManagerTestChild1.objects.create() self.child2 = InheritanceManagerTestChild2.objects.create() self.grandchild1 = InheritanceManagerTestGrandChild1.objects.create() self.grandchild1_2 = InheritanceManagerTestGrandChild1_2.objects.create() def test_select_subclass_by_child_model(self) -> None: """ Confirm that passing a child model works the same as passing the select_related manually """ objs = InheritanceManagerTestParent.objects.select_subclasses( "inheritancemanagertestchild1").order_by('pk') objsmodels = InheritanceManagerTestParent.objects.select_subclasses( InheritanceManagerTestChild1).order_by('pk') self.assertEqual(objs.subclasses, objsmodels.subclasses) self.assertEqual(list(objs), list(objsmodels)) def test_select_subclass_by_grandchild_model(self) -> None: """ Confirm that passing a grandchild model works the same as passing the select_related manually """ objs = InheritanceManagerTestParent.objects.select_subclasses( "inheritancemanagertestchild1__inheritancemanagertestgrandchild1") \ .order_by('pk') objsmodels = InheritanceManagerTestParent.objects.select_subclasses( InheritanceManagerTestGrandChild1).order_by('pk') self.assertEqual(objs.subclasses, objsmodels.subclasses) self.assertEqual(list(objs), list(objsmodels)) def test_selecting_all_subclasses_specifically_grandchildren(self) -> None: """ A bare select_subclasses() should achieve the same results as doing select_subclasses and specifying all possible subclasses. This test checks grandchildren, so only works on 1.6>= """ objs = InheritanceManagerTestParent.objects.select_subclasses().order_by('pk') objsmodels = InheritanceManagerTestParent.objects.select_subclasses( InheritanceManagerTestChild1, InheritanceManagerTestChild2, InheritanceManagerTestChild3, InheritanceManagerTestChild3_1, InheritanceManagerTestChild4, InheritanceManagerTestGrandChild1, InheritanceManagerTestGrandChild1_2).order_by('pk') self.assertEqual(set(objs.subclasses), set(objsmodels.subclasses)) self.assertEqual(list(objs), list(objsmodels)) def test_selecting_all_subclasses_specifically_children(self) -> None: """ A bare select_subclasses() should achieve the same results as doing select_subclasses and specifying all possible subclasses. Note: This is sort of the same test as `test_selecting_all_subclasses_specifically_grandchildren` but it specifically switches what models are used because that happens behind the scenes in a bare select_subclasses(), so we need to emulate it. """ objs = InheritanceManagerTestParent.objects.select_subclasses().order_by('pk') models = (InheritanceManagerTestChild1, InheritanceManagerTestChild2, InheritanceManagerTestChild3, InheritanceManagerTestChild3_1, InheritanceManagerTestChild4, InheritanceManagerTestGrandChild1, InheritanceManagerTestGrandChild1_2) objsmodels = InheritanceManagerTestParent.objects.select_subclasses( *models).order_by('pk') # order shouldn't matter, I don't think, as long as the resulting # queryset (when cast to a list) is the same. self.assertEqual(set(objs.subclasses), set(objsmodels.subclasses)) self.assertEqual(list(objs), list(objsmodels)) def test_select_subclass_just_self(self) -> None: """ Passing in the same model as the manager/queryset is bound against (ie: the root parent) should have no effect on the result set. """ objsmodels = InheritanceManagerTestParent.objects.select_subclasses( InheritanceManagerTestParent).order_by('pk') self.assertEqual([], objsmodels.subclasses) self.assertEqual(list(objsmodels), [ InheritanceManagerTestParent(pk=self.parent1.pk), InheritanceManagerTestParent(pk=self.child1.pk), InheritanceManagerTestParent(pk=self.child2.pk), InheritanceManagerTestParent(pk=self.grandchild1.pk), InheritanceManagerTestParent(pk=self.grandchild1_2.pk), ]) def test_select_subclass_invalid_related_model(self) -> None: """ Confirming that giving a stupid model doesn't work. """ regex = '^.+? is not a subclass of .+$' with self.assertRaisesRegex(ValueError, regex): InheritanceManagerTestParent.objects.select_subclasses( TimeFrame).order_by('pk') def test_mixing_strings_and_classes_with_grandchildren(self) -> None: """ Given arguments consisting of both strings and model classes, ensure the right resolutions take place, accounting for the extra depth (grandchildren etc) 1.6> allows. """ objs = InheritanceManagerTestParent.objects.select_subclasses( "inheritancemanagertestchild2", InheritanceManagerTestGrandChild1_2).order_by('pk') expecting = ['inheritancemanagertestchild1__inheritancemanagertestgrandchild1_2', 'inheritancemanagertestchild2'] self.assertEqual(set(objs.subclasses), set(expecting)) expecting2 = [ InheritanceManagerTestParent(pk=self.parent1.pk), InheritanceManagerTestParent(pk=self.child1.pk), InheritanceManagerTestChild2(pk=self.child2.pk), InheritanceManagerTestParent(pk=self.grandchild1.pk), InheritanceManagerTestGrandChild1_2(pk=self.grandchild1_2.pk), ] self.assertEqual(list(objs), expecting2) def test_mixing_strings_and_classes_with_children(self) -> None: """ Given arguments consisting of both strings and model classes, ensure the right resolutions take place, walking down as far as children. """ objs = InheritanceManagerTestParent.objects.select_subclasses( "inheritancemanagertestchild2", InheritanceManagerTestChild1).order_by('pk') expecting = ['inheritancemanagertestchild1', 'inheritancemanagertestchild2'] self.assertEqual(set(objs.subclasses), set(expecting)) expecting2 = [ InheritanceManagerTestParent(pk=self.parent1.pk), InheritanceManagerTestChild1(pk=self.child1.pk), InheritanceManagerTestChild2(pk=self.child2.pk), InheritanceManagerTestChild1(pk=self.grandchild1.pk), InheritanceManagerTestChild1(pk=self.grandchild1_2.pk), ] self.assertEqual(list(objs), expecting2) def test_duplications(self) -> None: """ Check that even if the same thing is provided as a string and a model that the right results are retrieved. """ # mixing strings and models which evaluate to the same thing is fine. objs = InheritanceManagerTestParent.objects.select_subclasses( "inheritancemanagertestchild2", InheritanceManagerTestChild2).order_by('pk') self.assertEqual(list(objs), [ InheritanceManagerTestParent(pk=self.parent1.pk), InheritanceManagerTestParent(pk=self.child1.pk), InheritanceManagerTestChild2(pk=self.child2.pk), InheritanceManagerTestParent(pk=self.grandchild1.pk), InheritanceManagerTestParent(pk=self.grandchild1_2.pk), ]) def test_child_doesnt_accidentally_get_parent(self) -> None: """ Given a Child model which also has an InheritanceManager, none of the returned objects should be Parent objects. """ objs = InheritanceManagerTestChild1.objects.select_subclasses( InheritanceManagerTestGrandChild1).order_by('pk') self.assertEqual([ InheritanceManagerTestChild1(pk=self.child1.pk), InheritanceManagerTestGrandChild1(pk=self.grandchild1.pk), InheritanceManagerTestChild1(pk=self.grandchild1_2.pk), ], list(objs)) def test_manually_specifying_parent_fk_only_specific_child(self) -> None: """ given a Model which inherits from another Model, but also declares the OneToOne link manually using `related_name` and `parent_link`, ensure that the relation names and subclasses are obtained correctly. """ child3 = InheritanceManagerTestChild3.objects.create() results = InheritanceManagerTestParent.objects.all().select_subclasses( InheritanceManagerTestChild3).order_by('pk') expected_objs = [ InheritanceManagerTestParent(pk=self.parent1.pk), InheritanceManagerTestParent(pk=self.child1.pk), InheritanceManagerTestParent(pk=self.child2.pk), InheritanceManagerTestParent(pk=self.grandchild1.pk), InheritanceManagerTestParent(pk=self.grandchild1_2.pk), child3 ] self.assertEqual(list(results), expected_objs) expected_related_names = ['manual_onetoone'] self.assertEqual(set(results.subclasses), set(expected_related_names)) def test_extras_descend(self) -> None: """ Ensure that extra(select=) values are copied onto sub-classes. """ results = InheritanceManagerTestParent.objects.select_subclasses().extra( select={'foo': 'id + 1'} ) self.assertTrue(all(result.foo == (result.id + 1) for result in results)) def test_limit_to_specific_subclass(self) -> None: child3 = InheritanceManagerTestChild3.objects.create() results = InheritanceManagerTestParent.objects.instance_of(InheritanceManagerTestChild3) self.assertEqual([child3], list(results)) def test_limit_to_specific_subclass_with_custom_db_column(self) -> None: item = InheritanceManagerTestChild3_1.objects.create() results = InheritanceManagerTestParent.objects.instance_of(InheritanceManagerTestChild3_1) self.assertEqual([item], list(results)) def test_limit_to_specific_grandchild_class(self) -> None: grandchild1 = InheritanceManagerTestGrandChild1.objects.get() results = InheritanceManagerTestParent.objects.instance_of(InheritanceManagerTestGrandChild1) self.assertEqual([grandchild1], list(results)) def test_limit_to_child_fetches_grandchildren_as_child_class(self) -> None: # Not sure if this is the desired behaviour...? children = InheritanceManagerTestChild1.objects.all() results = InheritanceManagerTestParent.objects.instance_of(InheritanceManagerTestChild1) self.assertEqual(set(children), set(results)) def test_can_fetch_limited_class_grandchildren(self) -> None: # Not sure if this is the desired behaviour...? children = InheritanceManagerTestChild1.objects.select_subclasses() results = InheritanceManagerTestParent.objects.instance_of(InheritanceManagerTestChild1).select_subclasses() self.assertEqual(set(children), set(results)) def test_selecting_multiple_instance_classes(self) -> None: child3 = InheritanceManagerTestChild3.objects.create() children1 = InheritanceManagerTestChild1.objects.all() results = InheritanceManagerTestParent.objects.instance_of(InheritanceManagerTestChild3, InheritanceManagerTestChild1) self.assertEqual(set([child3] + list(children1)), set(results)) def test_selecting_multiple_instance_classes_including_grandchildren(self) -> None: child3 = InheritanceManagerTestChild3.objects.create() grandchild1 = InheritanceManagerTestGrandChild1.objects.get() results = InheritanceManagerTestParent.objects.instance_of(InheritanceManagerTestChild3, InheritanceManagerTestGrandChild1).select_subclasses() self.assertEqual({child3, grandchild1}, set(results)) def test_select_subclasses_interaction_with_instance_of(self) -> None: child3 = InheritanceManagerTestChild3.objects.create() results = InheritanceManagerTestParent.objects.select_subclasses(InheritanceManagerTestChild1).instance_of(InheritanceManagerTestChild3) self.assertEqual({child3}, set(results)) class InheritanceManagerRelatedTests(InheritanceManagerTests): def setUp(self) -> None: self.related = InheritanceManagerTestRelated.objects.create() self.child1 = InheritanceManagerTestChild1.objects.create( related=self.related) self.child2 = InheritanceManagerTestChild2.objects.create( related=self.related) self.grandchild1 = InheritanceManagerTestGrandChild1.objects.create(related=self.related) self.grandchild1_2 = InheritanceManagerTestGrandChild1_2.objects.create(related=self.related) def get_manager(self) -> RelatedManager[InheritanceManagerTestParent]: # type: ignore[override] return self.related.imtests def test_get_method_with_select_subclasses(self) -> None: self.assertEqual( InheritanceManagerTestParent.objects.select_subclasses().get( id=self.child1.id), self.child1) def test_get_method_with_select_subclasses_check_for_useless_join(self) -> None: child4 = InheritanceManagerTestChild4.objects.create(related=self.related, other_onetoone=self.child1) self.assertEqual( str(InheritanceManagerTestChild4.objects.select_subclasses().filter( id=child4.id).query), str(InheritanceManagerTestChild4.objects.select_subclasses().select_related(None).filter( id=child4.id).query)) def test_annotate_with_select_subclasses(self) -> None: qs = InheritanceManagerTestParent.objects.select_subclasses().annotate( models.Count('id')) self.assertEqual(qs.get(id=self.child1.id).id__count, 1) def test_annotate_with_named_arguments_with_select_subclasses(self) -> None: qs = InheritanceManagerTestParent.objects.select_subclasses().annotate( test_count=models.Count('id')) self.assertEqual(qs.get(id=self.child1.id).test_count, 1) def test_annotate_before_select_subclasses(self) -> None: qs = InheritanceManagerTestParent.objects.annotate( models.Count('id')).select_subclasses() self.assertEqual(qs.get(id=self.child1.id).id__count, 1) def test_annotate_with_named_arguments_before_select_subclasses(self) -> None: qs = InheritanceManagerTestParent.objects.annotate( test_count=models.Count('id')).select_subclasses() self.assertEqual(qs.get(id=self.child1.id).test_count, 1) def test_clone_when_inheritance_queryset_selects_subclasses_should_clone_them_too(self) -> None: qs = InheritanceManagerTestParent.objects.select_subclasses() self.assertEqual(qs.subclasses, qs._clone().subclasses) jazzband-django-model-utils-aeef108/tests/test_managers/test_join_manager.py000066400000000000000000000025341466577571100275730ustar00rootroot00000000000000from __future__ import annotations from django.test import TestCase from tests.models import BoxJoinModel, JoinItemForeignKey class JoinManagerTest(TestCase): def setUp(self) -> None: for i in range(20): BoxJoinModel.objects.create(name=f'name_{i}') JoinItemForeignKey.objects.create( weight=10, belonging=BoxJoinModel.objects.get(name='name_1') ) JoinItemForeignKey.objects.create(weight=20) def test_self_join(self) -> None: a_slice = BoxJoinModel.objects.all()[0:10] with self.assertNumQueries(1): result = a_slice.join() self.assertEqual(result.count(), 10) def test_self_join_with_where_statement(self) -> None: qs = BoxJoinModel.objects.filter(name='name_1') result = qs.join() self.assertEqual(result.count(), 1) def test_join_with_other_qs(self) -> None: item_qs = JoinItemForeignKey.objects.filter(weight=10) boxes = BoxJoinModel.objects.all().join(qs=item_qs) self.assertEqual(boxes.count(), 1) self.assertEqual(boxes[0].name, 'name_1') def test_reverse_join(self) -> None: box_qs = BoxJoinModel.objects.filter(name='name_1') items = JoinItemForeignKey.objects.all().join(box_qs) self.assertEqual(items.count(), 1) self.assertEqual(items[0].weight, 10) jazzband-django-model-utils-aeef108/tests/test_managers/test_query_manager.py000066400000000000000000000015561466577571100300040ustar00rootroot00000000000000from __future__ import annotations from django.test import TestCase from tests.models import Post class QueryManagerTests(TestCase): def setUp(self) -> None: data = ((True, True, 0), (True, False, 4), (False, False, 2), (False, True, 3), (True, True, 1), (True, False, 5)) for p, c, o in data: Post.objects.create(published=p, confirmed=c, order=o) def test_passing_kwargs(self) -> None: qs = Post.public.all() self.assertEqual([p.order for p in qs], [0, 1, 4, 5]) def test_passing_Q(self) -> None: qs = Post.public_confirmed.all() self.assertEqual([p.order for p in qs], [0, 1]) def test_ordering(self) -> None: qs = Post.public_reversed.all() self.assertEqual([p.order for p in qs], [5, 4, 1, 0]) jazzband-django-model-utils-aeef108/tests/test_managers/test_softdelete_manager.py000066400000000000000000000020401466577571100307620ustar00rootroot00000000000000from __future__ import annotations from django.test import TestCase from tests.models import CustomSoftDelete class CustomSoftDeleteManagerTests(TestCase): def test_custom_manager_empty(self) -> None: qs = CustomSoftDelete.available_objects.only_read() self.assertEqual(qs.count(), 0) def test_custom_qs_empty(self) -> None: qs = CustomSoftDelete.available_objects.all().only_read() self.assertEqual(qs.count(), 0) def test_is_read(self) -> None: for is_read in [True, False, True, False]: CustomSoftDelete.available_objects.create(is_read=is_read) qs = CustomSoftDelete.available_objects.only_read() self.assertEqual(qs.count(), 2) def test_is_read_removed(self) -> None: for is_read, is_removed in [(True, True), (True, False), (False, False), (False, True)]: CustomSoftDelete.available_objects.create(is_read=is_read, is_removed=is_removed) qs = CustomSoftDelete.available_objects.only_read() self.assertEqual(qs.count(), 1) jazzband-django-model-utils-aeef108/tests/test_managers/test_status_manager.py000066400000000000000000000014131466577571100301520ustar00rootroot00000000000000from __future__ import annotations from django.core.exceptions import ImproperlyConfigured from django.db import models from django.test import TestCase from model_utils.managers import QueryManager from model_utils.models import StatusModel from tests.models import StatusManagerAdded class StatusManagerAddedTests(TestCase): def test_manager_available(self) -> None: self.assertTrue(isinstance(StatusManagerAdded.active, QueryManager)) def test_conflict_error(self) -> None: with self.assertRaises(ImproperlyConfigured): class ErrorModel(StatusModel): STATUS = ( ('active', 'Is Active'), ('deleted', 'Is Deleted'), ) active = models.BooleanField() jazzband-django-model-utils-aeef108/tests/test_miscellaneous.py000066400000000000000000000016711466577571100251520ustar00rootroot00000000000000from __future__ import annotations from django.core.management import call_command from django.test import TestCase from model_utils.fields import get_excerpt class MigrationsTests(TestCase): def test_makemigrations(self) -> None: call_command('makemigrations', dry_run=True) class GetExcerptTests(TestCase): def test_split(self) -> None: e = get_excerpt("some content\n\n\n\nsome more") self.assertEqual(e, 'some content\n') def test_auto_split(self) -> None: e = get_excerpt("para one\n\npara two\n\npara three") self.assertEqual(e, 'para one\n\npara two') def test_middle_of_para(self) -> None: e = get_excerpt("some text\n\nmore text") self.assertEqual(e, 'some text') def test_middle_of_line(self) -> None: e = get_excerpt("some text more text") self.assertEqual(e, "some text more text") jazzband-django-model-utils-aeef108/tests/test_models/000077500000000000000000000000001466577571100232135ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/tests/test_models/__init__.py000066400000000000000000000000001466577571100253120ustar00rootroot00000000000000jazzband-django-model-utils-aeef108/tests/test_models/test_deferred_fields.py000066400000000000000000000052161466577571100277360ustar00rootroot00000000000000from __future__ import annotations from django.test import TestCase from tests.models import ModelWithCustomDescriptor class CustomDescriptorTests(TestCase): def setUp(self) -> None: self.instance = ModelWithCustomDescriptor.objects.create( custom_field='1', tracked_custom_field='1', regular_field=1, tracked_regular_field=1, ) def test_custom_descriptor_works(self) -> None: instance = self.instance self.assertEqual(instance.custom_field, '1') self.assertEqual(instance.__dict__['custom_field'], 1) self.assertEqual(instance.regular_field, 1) instance.custom_field = 2 self.assertEqual(instance.custom_field, '2') self.assertEqual(instance.__dict__['custom_field'], 2) instance.save() instance = ModelWithCustomDescriptor.objects.get(pk=instance.pk) self.assertEqual(instance.custom_field, '2') self.assertEqual(instance.__dict__['custom_field'], 2) def test_deferred(self) -> None: instance = ModelWithCustomDescriptor.objects.only('id').get( pk=self.instance.pk) self.assertIn('custom_field', instance.get_deferred_fields()) self.assertEqual(instance.custom_field, '1') self.assertNotIn('custom_field', instance.get_deferred_fields()) self.assertEqual(instance.regular_field, 1) self.assertEqual(instance.tracked_custom_field, '1') self.assertEqual(instance.tracked_regular_field, 1) self.assertFalse(instance.tracker.has_changed('tracked_custom_field')) self.assertFalse(instance.tracker.has_changed('tracked_regular_field')) instance.tracked_custom_field = 2 instance.tracked_regular_field = 2 self.assertTrue(instance.tracker.has_changed('tracked_custom_field')) self.assertTrue(instance.tracker.has_changed('tracked_regular_field')) instance.save() instance = ModelWithCustomDescriptor.objects.get(pk=instance.pk) self.assertEqual(instance.custom_field, '1') self.assertEqual(instance.regular_field, 1) self.assertEqual(instance.tracked_custom_field, '2') self.assertEqual(instance.tracked_regular_field, 2) instance = ModelWithCustomDescriptor.objects.only('id').get(pk=instance.pk) instance.tracked_custom_field = 3 self.assertEqual(instance.tracked_custom_field, '3') self.assertTrue(instance.tracker.has_changed('tracked_custom_field')) del instance.tracked_custom_field self.assertEqual(instance.tracked_custom_field, '2') self.assertFalse(instance.tracker.has_changed('tracked_custom_field')) jazzband-django-model-utils-aeef108/tests/test_models/test_softdeletable_model.py000066400000000000000000000044711466577571100306270ustar00rootroot00000000000000from __future__ import annotations from django.test import TestCase from django.utils.connection import ConnectionDoesNotExist from tests.models import SoftDeletable class SoftDeletableModelTests(TestCase): def test_can_only_see_not_removed_entries(self) -> None: SoftDeletable.available_objects.create(name='a', is_removed=True) SoftDeletable.available_objects.create(name='b', is_removed=False) queryset = SoftDeletable.available_objects.all() self.assertEqual(queryset.count(), 1) self.assertEqual(queryset[0].name, 'b') def test_instance_cannot_be_fully_deleted(self) -> None: instance = SoftDeletable.available_objects.create(name='a') instance.delete() self.assertEqual(SoftDeletable.available_objects.count(), 0) self.assertEqual(SoftDeletable.all_objects.count(), 1) def test_instance_cannot_be_fully_deleted_via_queryset(self) -> None: SoftDeletable.available_objects.create(name='a') SoftDeletable.available_objects.all().delete() self.assertEqual(SoftDeletable.available_objects.count(), 0) self.assertEqual(SoftDeletable.all_objects.count(), 1) def test_delete_instance_no_connection(self) -> None: obj = SoftDeletable.available_objects.create(name='a') self.assertRaises(ConnectionDoesNotExist, obj.delete, using='other') def test_instance_purge(self) -> None: instance = SoftDeletable.available_objects.create(name='a') instance.delete(soft=False) self.assertEqual(SoftDeletable.available_objects.count(), 0) self.assertEqual(SoftDeletable.all_objects.count(), 0) def test_instance_purge_no_connection(self) -> None: instance = SoftDeletable.available_objects.create(name='a') self.assertRaises(ConnectionDoesNotExist, instance.delete, using='other', soft=False) def test_deprecation_warning(self) -> None: self.assertWarns(DeprecationWarning, SoftDeletable.objects.all) def test_delete_queryset_return(self) -> None: SoftDeletable.available_objects.create(name='a') SoftDeletable.available_objects.create(name='b') result = SoftDeletable.available_objects.filter(name="a").delete() assert result == ( 1, {SoftDeletable._meta.label: 1} ) jazzband-django-model-utils-aeef108/tests/test_models/test_status_model.py000066400000000000000000000102731466577571100273320ustar00rootroot00000000000000from __future__ import annotations from datetime import datetime, timezone import time_machine from django.test.testcases import TestCase from tests.models import CustomManagerStatusModel, Status, StatusPlainTuple class StatusModelTests(TestCase): model: type[Status] | type[StatusPlainTuple] def setUp(self) -> None: self.model = Status self.on_hold = Status.STATUS.on_hold self.active = Status.STATUS.active def test_created(self) -> None: with time_machine.travel(datetime(2016, 1, 1)): c1 = self.model.objects.create() self.assertTrue(c1.status_changed, datetime(2016, 1, 1)) self.model.objects.create() self.assertEqual(self.model.active.count(), 2) self.assertEqual(self.model.deleted.count(), 0) def test_modification(self) -> None: t1 = self.model.objects.create() date_created = t1.status_changed t1.status = self.on_hold t1.save() self.assertEqual(self.model.active.count(), 0) self.assertEqual(self.model.on_hold.count(), 1) self.assertTrue(t1.status_changed > date_created) date_changed = t1.status_changed t1.save() self.assertEqual(t1.status_changed, date_changed) date_active_again = t1.status_changed t1.status = self.active t1.save() self.assertTrue(t1.status_changed > date_active_again) def test_save_with_update_fields_overrides_status_changed_provided(self) -> None: ''' Tests if the save method updated status_changed field accordingly when update_fields is used as an argument and status_changed is provided ''' with time_machine.travel(datetime(2020, 1, 1, tzinfo=timezone.utc)): t1 = Status.objects.create() with time_machine.travel(datetime(2020, 1, 2, tzinfo=timezone.utc)): t1.status = Status.on_hold t1.save(update_fields=['status', 'status_changed']) self.assertEqual(t1.status_changed, datetime(2020, 1, 2, tzinfo=timezone.utc)) def test_save_with_update_fields_overrides_status_changed_not_provided(self) -> None: ''' Tests if the save method updated status_changed field accordingly when update_fields is used as an argument with status and status_changed is not provided ''' with time_machine.travel(datetime(2020, 1, 1, tzinfo=timezone.utc)): t1 = Status.objects.create() with time_machine.travel(datetime(2020, 1, 2, tzinfo=timezone.utc)): t1.status = Status.on_hold t1.save(update_fields=['status']) self.assertEqual(t1.status_changed, datetime(2020, 1, 2, tzinfo=timezone.utc)) class StatusModelPlainTupleTests(StatusModelTests): def setUp(self) -> None: self.model = StatusPlainTuple self.on_hold = StatusPlainTuple.STATUS[2][0] self.active = StatusPlainTuple.STATUS[0][0] class StatusModelDefaultManagerTests(TestCase): def test_default_manager_is_not_status_model_generated_ones(self) -> None: # Regression test for GH-251 # The logic behind order for managers seems to have changed in Django 1.10 # and affects default manager. # This code was previously failing because the first custom manager (which filters # with first Choice value, here 'first_choice') generated by StatusModel was # considered as default manager... # This situation only happens when we define a model inheriting from an "abstract" # class which defines an "objects" manager. CustomManagerStatusModel.objects.create(status='first_choice') CustomManagerStatusModel.objects.create(status='second_choice') CustomManagerStatusModel.objects.create(status='second_choice') # ...which made this count() equal to 1 (only 1 element with status='first_choice')... self.assertEqual(CustomManagerStatusModel._default_manager.count(), 3) # ...and this one equal to 0, because of 2 successive filters of 'first_choice' # (default manager) and 'second_choice' (explicit filter below). self.assertEqual(CustomManagerStatusModel._default_manager.filter(status='second_choice').count(), 2) jazzband-django-model-utils-aeef108/tests/test_models/test_timeframed_model.py000066400000000000000000000032671466577571100301310ustar00rootroot00000000000000from __future__ import annotations from datetime import datetime, timedelta from django.core.exceptions import ImproperlyConfigured from django.db import models from django.test import TestCase from model_utils.managers import QueryManager from model_utils.models import TimeFramedModel from tests.models import TimeFrame, TimeFrameManagerAdded class TimeFramedModelTests(TestCase): def setUp(self) -> None: self.now = datetime.now() def test_not_yet_begun(self) -> None: TimeFrame.objects.create(start=self.now + timedelta(days=2)) self.assertEqual(TimeFrame.timeframed.count(), 0) def test_finished(self) -> None: TimeFrame.objects.create(end=self.now - timedelta(days=1)) self.assertEqual(TimeFrame.timeframed.count(), 0) def test_no_end(self) -> None: TimeFrame.objects.create(start=self.now - timedelta(days=10)) self.assertEqual(TimeFrame.timeframed.count(), 1) def test_no_start(self) -> None: TimeFrame.objects.create(end=self.now + timedelta(days=2)) self.assertEqual(TimeFrame.timeframed.count(), 1) def test_within_range(self) -> None: TimeFrame.objects.create(start=self.now - timedelta(days=1), end=self.now + timedelta(days=1)) self.assertEqual(TimeFrame.timeframed.count(), 1) class TimeFrameManagerAddedTests(TestCase): def test_manager_available(self) -> None: self.assertTrue(isinstance(TimeFrameManagerAdded.timeframed, QueryManager)) def test_conflict_error(self) -> None: with self.assertRaises(ImproperlyConfigured): class ErrorModel(TimeFramedModel): timeframed = models.BooleanField() jazzband-django-model-utils-aeef108/tests/test_models/test_timestamped_model.py000066400000000000000000000140251466577571100303220ustar00rootroot00000000000000from __future__ import annotations from collections.abc import Iterable from datetime import datetime, timedelta, timezone import time_machine from django.test import TestCase from tests.models import TimeStamp, TimeStampWithStatusModel class TimeStampedModelTests(TestCase): def test_created(self) -> None: with time_machine.travel(datetime(2016, 1, 1, tzinfo=timezone.utc)): t1 = TimeStamp.objects.create() self.assertEqual(t1.created, datetime(2016, 1, 1, tzinfo=timezone.utc)) def test_created_sets_modified(self) -> None: ''' Ensure that on creation that modified is set exactly equal to created. ''' t1 = TimeStamp.objects.create() self.assertEqual(t1.created, t1.modified) def test_modified(self) -> None: with time_machine.travel(datetime(2016, 1, 1, tzinfo=timezone.utc)): t1 = TimeStamp.objects.create() with time_machine.travel(datetime(2016, 1, 2, tzinfo=timezone.utc)): t1.save() self.assertEqual(t1.modified, datetime(2016, 1, 2, tzinfo=timezone.utc)) def test_overriding_created_via_object_creation_also_uses_creation_date_for_modified(self) -> None: """ Setting the created date when first creating an object should be permissible. """ different_date = datetime.today() - timedelta(weeks=52) t1 = TimeStamp.objects.create(created=different_date) self.assertEqual(t1.created, different_date) self.assertEqual(t1.modified, different_date) def test_overriding_modified_via_object_creation(self) -> None: """ Setting the modified date explicitly should be possible when first creating an object, but not thereafter. """ different_date = datetime.today() - timedelta(weeks=52) t1 = TimeStamp.objects.create(modified=different_date) self.assertEqual(t1.modified, different_date) self.assertNotEqual(t1.created, different_date) def test_overriding_created_after_object_created(self) -> None: """ The created date may be changed post-create """ t1 = TimeStamp.objects.create() different_date = datetime.today() - timedelta(weeks=52) t1.created = different_date t1.save() self.assertEqual(t1.created, different_date) def test_overriding_modified_after_object_created(self) -> None: """ The modified date should always be updated when the object is saved, regardless of attempts to change it. """ t1 = TimeStamp.objects.create() different_date = datetime.today() - timedelta(weeks=52) t1.modified = different_date t1.save() self.assertNotEqual(t1.modified, different_date) def test_overrides_using_save(self) -> None: """ The first time an object is saved, allow modification of both created and modified fields. After that, only created may be modified manually. """ t1 = TimeStamp() different_date = datetime.today() - timedelta(weeks=52) t1.created = different_date t1.modified = different_date t1.save() self.assertEqual(t1.created, different_date) self.assertEqual(t1.modified, different_date) different_date2 = datetime.today() - timedelta(weeks=26) t1.created = different_date2 t1.modified = different_date2 t1.save() self.assertEqual(t1.created, different_date2) self.assertNotEqual(t1.modified, different_date2) self.assertNotEqual(t1.modified, different_date) def test_save_with_update_fields_overrides_modified_provided_within_a(self) -> None: """ Tests if the save method updated modified field accordingly when update_fields is used as an argument and modified is provided """ tests = ( ['modified'], # list ('modified',), # tuple {'modified'}, # set ) for update_fields in tests: with self.subTest(update_fields=update_fields): with time_machine.travel(datetime(2020, 1, 1, tzinfo=timezone.utc)): t1 = TimeStamp.objects.create() with time_machine.travel(datetime(2020, 1, 2, tzinfo=timezone.utc)): t1.save(update_fields=update_fields) self.assertEqual(t1.modified, datetime(2020, 1, 2, tzinfo=timezone.utc)) def test_save_is_skipped_for_empty_update_fields_iterable(self) -> None: tests: Iterable[Iterable[str]] = ( [], # list (), # tuple set(), # set ) for update_fields in tests: with self.subTest(update_fields=update_fields): with time_machine.travel(datetime(2020, 1, 1, tzinfo=timezone.utc)): t1 = TimeStamp.objects.create() with time_machine.travel(datetime(2020, 1, 2, tzinfo=timezone.utc)): t1.test_field = 1 t1.save(update_fields=update_fields) t1.refresh_from_db() self.assertEqual(t1.test_field, 0) self.assertEqual(t1.modified, datetime(2020, 1, 1, tzinfo=timezone.utc)) def test_save_updates_modified_value_when_update_fields_explicitly_set_to_none(self) -> None: with time_machine.travel(datetime(2020, 1, 1, tzinfo=timezone.utc)): t1 = TimeStamp.objects.create() with time_machine.travel(datetime(2020, 1, 2, tzinfo=timezone.utc)): t1.save(update_fields=None) self.assertEqual(t1.modified, datetime(2020, 1, 2, tzinfo=timezone.utc)) def test_model_inherit_timestampmodel_and_statusmodel(self) -> None: with time_machine.travel(datetime(2020, 1, 1, tzinfo=timezone.utc)): t1 = TimeStampWithStatusModel.objects.create() with time_machine.travel(datetime(2020, 1, 2, tzinfo=timezone.utc)): t1.save(update_fields=['test_field', 'status']) self.assertEqual(t1.modified, datetime(2020, 1, 2, tzinfo=timezone.utc)) jazzband-django-model-utils-aeef108/tests/test_models/test_uuid_model.py000066400000000000000000000012611466577571100267520ustar00rootroot00000000000000from __future__ import annotations from django.test import TestCase from tests.models import CustomNotPrimaryUUIDModel, CustomUUIDModel class UUIDFieldTests(TestCase): def test_uuid_model_with_uuid_field_as_primary_key(self) -> None: instance = CustomUUIDModel() instance.save() self.assertEqual(instance.id.__class__.__name__, 'UUID') self.assertEqual(instance.id, instance.pk) def test_uuid_model_with_uuid_field_as_not_primary_key(self) -> None: instance = CustomNotPrimaryUUIDModel() instance.save() self.assertEqual(instance.uuid.__class__.__name__, 'UUID') self.assertNotEqual(instance.uuid, instance.pk) jazzband-django-model-utils-aeef108/tox.ini000066400000000000000000000024461466577571100210500ustar00rootroot00000000000000[tox] envlist = py{37,38,39,310}-dj32 py{38,39,310}-dj{40} py{38,39,310,311}-dj{41} py{38,39,310,311}-dj{42} py{310,311,312}-dj{50} py{310,311,312}-dj{51} py{310,311,312}-dj{main} flake8 isort mypy [gh-actions] python = 3.7: py37 3.8: py38, flake8, isort, mypy 3.9: py39 3.10: py310 3.11: py311 3.12: py312 [testenv] deps = time-machine==2.4.1 -rrequirements-test.txt dj32: Django==3.2.* dj40: Django==4.0.* dj41: Django==4.1.* dj42: Django==4.2.* dj50: Django==5.0.* dj51: Django==5.1.* djmain: https://github.com/django/django/archive/main.tar.gz ignore_outcome = djmain: True ignore_errors = djmain: True passenv = CI FORCE_COLOR GITHUB_* POSTGRES_* usedevelop = True commands = python -m pytest {posargs} [testenv:flake8] basepython = python3.8 deps = flake8 skip_install = True commands = flake8 model_utils tests [flake8] ignore = E731 W503 E402 E501 [testenv:isort] basepython = python3.8 deps = isort commands = isort model_utils tests setup.py --check-only --diff skip_install = True [testenv:mypy] basepython = python3.8 deps = time-machine==2.8.2 -r requirements-mypy.txt set_env = SQLITE=1 commands = mypy model_utils tests jazzband-django-model-utils-aeef108/translations.py000077500000000000000000000015461466577571100226330ustar00rootroot00000000000000#!/usr/bin/env python import os import sys from django.conf import settings import django DEFAULT_SETTINGS = dict( INSTALLED_APPS=( 'model_utils', 'tests', ), DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3" } }, SILENCED_SYSTEM_CHECKS=["1_7.W001"], ) def run(command): if not settings.configured: settings.configure(**DEFAULT_SETTINGS) parent = os.path.dirname(os.path.abspath(__file__)) appdir = os.path.join(parent, 'model_utils') os.chdir(appdir) from django.core.management import call_command call_command('%smessages' % command) if __name__ == '__main__': if (len(sys.argv)) < 2 or (sys.argv[1] not in {'make', 'compile'}): print("Run `translations.py make` or `translations.py compile`.") sys.exit(1) run(sys.argv[1])