pax_global_header00006660000000000000000000000064141307673360014524gustar00rootroot0000000000000052 comment=5ca515acc74297c08c6d6765365f681cdd4a80b9 django-model-utils-4.2.0/000077500000000000000000000000001413076733600152255ustar00rootroot00000000000000django-model-utils-4.2.0/.coveragerc000066400000000000000000000000411413076733600173410ustar00rootroot00000000000000[run] include = model_utils/*.py django-model-utils-4.2.0/.editorconfig000066400000000000000000000003561413076733600177060ustar00rootroot00000000000000# http://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 django-model-utils-4.2.0/.github/000077500000000000000000000000001413076733600165655ustar00rootroot00000000000000django-model-utils-4.2.0/.github/ISSUE_TEMPLATE.md000066400000000000000000000004521413076733600212730ustar00rootroot00000000000000## 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. django-model-utils-4.2.0/.github/PULL_REQUEST_TEMPLATE.md000066400000000000000000000007551413076733600223750ustar00rootroot00000000000000## 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). django-model-utils-4.2.0/.github/workflows/000077500000000000000000000000001413076733600206225ustar00rootroot00000000000000django-model-utils-4.2.0/.github/workflows/release.yml000066400000000000000000000017601413076733600227710ustar00rootroot00000000000000name: Release on: push: tags: - '*' jobs: build: if: github.repository == 'jazzband/django-model-utils' runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 with: fetch-depth: 0 - name: Set up Python uses: actions/setup-python@v2 with: python-version: 3.8 - 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 django-model-utils-4.2.0/.github/workflows/test.yml000066400000000000000000000032701413076733600223260ustar00rootroot00000000000000name: Test on: [push, pull_request] jobs: build: runs-on: ubuntu-latest strategy: fail-fast: false max-parallel: 5 matrix: python-version: ['3.6', '3.7', '3.8', '3.9', '3.10'] services: postgres: image: postgres:10 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: postgres ports: - 5432:5432 options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 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@v2 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: DB_NAME: postgres DB_USER: postgres DB_PASSWORD: postgres DB_HOST: localhost DB_PORT: 5432 - name: Upload coverage uses: codecov/codecov-action@v1 with: name: Python ${{ matrix.python-version }} django-model-utils-4.2.0/.gitignore000066400000000000000000000002141413076733600172120ustar00rootroot00000000000000dist/* build django_model_utils.egg-info/* HGREV .coverage .tox/ Django-*.egg *.pyc htmlcov/ docs/_build/ .idea/ .eggs/ .venv/ coverage.xml django-model-utils-4.2.0/AUTHORS.rst000066400000000000000000000076111413076733600171110ustar00rootroot00000000000000| 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 | Eran Rundstein | Eugene Kuznetsov | Felipe Prenholato | Filipe Ximenes | Germano Massullo | Gregor Müllegger | Guilherme Devincenzi | Hanley | Hanley Hansen | Harry Moreno | Hasan Ramezani | Ivan Virabyan | JMP | Jack Cushman | James Oakley | Jannis Leidel | Javier Garcia Sogo | Jeff Elmore | 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 django-model-utils-4.2.0/CHANGES.rst000066400000000000000000000363321413076733600170360ustar00rootroot00000000000000Changelog ========= Unreleased ---------- 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: http://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`` django-model-utils-4.2.0/CONTRIBUTING.rst000066400000000000000000000050621413076733600176710ustar00rootroot00000000000000Contributing ============ .. 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 **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 django-model-utils-4.2.0/LICENSE.txt000066400000000000000000000030011413076733600170420ustar00rootroot00000000000000Copyright (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. django-model-utils-4.2.0/MANIFEST.in000066400000000000000000000003551413076733600167660ustar00rootroot00000000000000include 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 django-model-utils-4.2.0/Makefile000066400000000000000000000012721413076733600166670ustar00rootroot00000000000000VIRTUALENV = 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 django-model-utils-4.2.0/README.rst000066400000000000000000000033051413076733600167150ustar00rootroot00000000000000================== 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`_ 2.2+. .. _Django: http://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/ Run tests --------- .. code-block pip install -e . py.test 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 django-model-utils-4.2.0/docs/000077500000000000000000000000001413076733600161555ustar00rootroot00000000000000django-model-utils-4.2.0/docs/Makefile000066400000000000000000000152321413076733600176200ustar00rootroot00000000000000# 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 http://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." django-model-utils-4.2.0/docs/changelog.rst000066400000000000000000000000521413076733600206330ustar00rootroot00000000000000.. changelog: .. include:: ../CHANGES.rstdjango-model-utils-4.2.0/docs/conf.py000066400000000000000000000176621413076733600174700ustar00rootroot00000000000000# # 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 from pkg_resources import get_distribution # 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 = get_distribution('django-model-utils').version # 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 django-model-utils-4.2.0/docs/fields.rst000066400000000000000000000143571413076733600201670ustar00rootroot00000000000000Fields ====== .. _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) django-model-utils-4.2.0/docs/index.rst000066400000000000000000000010721413076733600200160ustar00rootroot00000000000000================== 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` django-model-utils-4.2.0/docs/make.bat000066400000000000000000000145231413076733600175670ustar00rootroot00000000000000@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.http://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 django-model-utils-4.2.0/docs/managers.rst000066400000000000000000000132411413076733600205050ustar00rootroot00000000000000Model 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 heterogenous 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: http://jeffelmore.org/2010/11/11/automatic-downcasting-of-inherited-models-in-django/ JoinManager ----------- The ``JoinManager`` will create a temporary table of your current queryset and join that temporary table with the model of your current queryset. 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 a queryset and the manager will create a temporary table and join that to your current queryset. 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 .. _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. django-model-utils-4.2.0/docs/models.rst000066400000000000000000000073051413076733600201770ustar00rootroot00000000000000Models ====== 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. 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 SaveSignalHandlingModel ----------------------- An abstract base class model to pass a parameter ``signals_to_disable`` to ``save`` method in order to disable signals .. code-block:: python from model_utils.models import SaveSignalHandlingModel class SaveSignalTestModel(SaveSignalHandlingModel): name = models.CharField(max_length=20) obj = SaveSignalTestModel(name='Test') # Note: If you use `Model.objects.create`, the signals can't be disabled obj.save(signals_to_disable=['pre_save'] # disable `pre_save` signal django-model-utils-4.2.0/docs/setup.rst000066400000000000000000000007561413076733600200570ustar00rootroot00000000000000===== 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`_ 2.2, 3.1 and 3.2 (latest bugfix release in each series only) on Python 3.6+. .. _Django: http://www.djangoproject.com/ django-model-utils-4.2.0/docs/utilities.rst000066400000000000000000000334241413076733600207300ustar00rootroot00000000000000======================= 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`` and ``refresh_from_db`` methods to reset initial state for tracked fields. 2. In ``post_init`` handler ``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 = FieldsTracker() 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'): ... django-model-utils-4.2.0/model_utils/000077500000000000000000000000001413076733600175455ustar00rootroot00000000000000django-model-utils-4.2.0/model_utils/__init__.py000066400000000000000000000005271413076733600216620ustar00rootroot00000000000000from pkg_resources import DistributionNotFound, get_distribution from .choices import Choices # noqa:F401 from .tracker import FieldTracker, ModelTracker # noqa:F401 try: __version__ = get_distribution("django-model-utils").version except DistributionNotFound: # pragma: no cover # package is not installed __version__ = None django-model-utils-4.2.0/model_utils/choices.py000066400000000000000000000131531413076733600215370ustar00rootroot00000000000000import copy class Choices: """ 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. """ def __init__(self, *choices): # list of choices expanded to triples - can include optgroups self._triples = [] # list of choices as (db, human-readable) - can include optgroups self._doubles = [] # dictionary mapping db representation to human-readable self._display_map = {} # dictionary mapping Python identifier to db representation self._identifier_map = {} # set of db representations self._db_values = set() self._process(choices) def _store(self, triple, triple_collector, double_collector): 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, triple_collector=None, double_collector=None): if triple_collector is None: triple_collector = self._triples if double_collector is None: double_collector = self._doubles store = lambda c: self._store(c, triple_collector, double_collector) for choice in choices: 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 = [] triple_collector.append((group_name, tc)) dc = [] double_collector.append((group_name, dc)) self._process(subchoices, tc, dc) else: store((choice[0], choice[0], 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): return len(self._doubles) def __iter__(self): return iter(self._doubles) def __reversed__(self): return reversed(self._doubles) def __getattr__(self, attname): try: return self._identifier_map[attname] except KeyError: raise AttributeError(attname) def __getitem__(self, key): return self._display_map[key] def __add__(self, other): if isinstance(other, self.__class__): other = other._triples else: other = list(other) return Choices(*(self._triples + other)) def __radd__(self, other): # radd is never called for matching types, so we don't check here other = list(other) return Choices(*(other + self._triples)) def __eq__(self, other): if isinstance(other, self.__class__): return self._triples == other._triples return False def __repr__(self): return '{}({})'.format( self.__class__.__name__, ', '.join("%s" % repr(i) for i in self._triples) ) def __contains__(self, item): return item in self._db_values def __deepcopy__(self, memo): return self.__class__(*copy.deepcopy(self._triples, memo)) def subset(self, *new_identifiers): 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), ) return self.__class__(*[ choice for choice in self._triples if choice[1] in new_identifiers ]) django-model-utils-4.2.0/model_utils/fields.py000066400000000000000000000277301413076733600213760ustar00rootroot00000000000000import secrets import uuid from collections.abc import Callable from django.conf import settings from django.core.exceptions import ValidationError from django.db import models from django.utils.timezone import now DEFAULT_CHOICES_NAME = 'STATUS' class AutoCreatedField(models.DateTimeField): """ A DateTimeField that automatically populates itself at object creation. By default, sets editable=False, default=datetime.now. """ def __init__(self, *args, **kwargs): 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): """Return the default value for this field.""" if not hasattr(self, "_default"): self._default = self._get_default() return self._default def pre_save(self, model_instance, add): 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, **kwargs): kwargs.setdefault('max_length', 100) self.check_for_status = not kwargs.pop('no_check_for_status', False) self.choices_name = kwargs.pop('choices_name', DEFAULT_CHOICES_NAME) super().__init__(*args, **kwargs) def prepare_class(self, sender, **kwargs): 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, name): 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) def deconstruct(self): name, path, args, kwargs = super().deconstruct() kwargs['no_check_for_status'] = True return name, path, args, kwargs class MonitorField(models.DateTimeField): """ 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, **kwargs): kwargs.setdefault('default', now) monitor = kwargs.pop('monitor', None) if not monitor: raise TypeError( '%s requires a "monitor" argument' % self.__class__.__name__) self.monitor = monitor when = kwargs.pop('when', None) if when is not None: when = set(when) self.when = when super().__init__(*args, **kwargs) def contribute_to_class(self, cls, name): self.monitor_attname = '_monitor_%s' % name models.signals.post_init.connect(self._save_initial, sender=cls) super().contribute_to_class(cls, name) def get_monitored_value(self, instance): return getattr(instance, self.monitor) def _save_initial(self, sender, instance, **kwargs): 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, add): 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): 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): return '_%s_excerpt' % name def get_excerpt(content): excerpt = [] 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, field_name, excerpt_field_name): # 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 # content is read/write @property def content(self): return self.instance.__dict__[self.field_name] @content.setter def content(self, val): setattr(self.instance, self.field_name, val) # excerpt is a read only property def _get_excerpt(self): return getattr(self.instance, self.excerpt_field_name) excerpt = property(_get_excerpt) # has_more is a boolean property def _get_has_more(self): return self.excerpt.strip() != self.content.strip() has_more = property(_get_has_more) def __str__(self): return self.content class SplitDescriptor: def __init__(self, field): self.field = field self.excerpt_field_name = _excerpt_field_name(self.field.name) def __get__(self, instance, owner): if instance is None: raise AttributeError('Can only be accessed via an instance.') content = instance.__dict__[self.field.name] if content is None: return None return SplitText(instance, self.field.name, self.excerpt_field_name) def __set__(self, obj, value): 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 class SplitField(models.TextField): def __init__(self, *args, **kwargs): # for South FakeORM compatibility: the frozen version of a # SplitField can't try to add an _excerpt field, because the # _excerpt field itself is frozen as well. See introspection # rules below. self.add_excerpt_field = not kwargs.pop('no_excerpt_field', False) super().__init__(*args, **kwargs) def contribute_to_class(self, cls, name): if self.add_excerpt_field and not cls._meta.abstract: excerpt_field = models.TextField(editable=False) cls.add_to_class(_excerpt_field_name(name), excerpt_field) super().contribute_to_class(cls, name) setattr(cls, self.name, SplitDescriptor(self)) def pre_save(self, model_instance, add): value = 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): value = self.value_from_object(obj) return value.content def get_prep_value(self, value): try: return value.content except AttributeError: return value def deconstruct(self): name, path, args, kwargs = super().deconstruct() kwargs['no_excerpt_field'] = True return name, path, args, kwargs class UUIDField(models.UUIDField): """ A field for storing universally unique identifiers. Use Python UUID class. """ def __init__(self, primary_key=True, version=4, editable=False, *args, **kwargs): """ 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.') 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. """ def __init__(self, editable=False, max_length=128, factory=None, **kwargs): """ 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 isinstance(factory, Callable): raise TypeError("'factory' should either be a callable not '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): 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): name, path, args, kwargs = super().deconstruct() kwargs['factory'] = self._factory return name, path, args, kwargs django-model-utils-4.2.0/model_utils/locale/000077500000000000000000000000001413076733600210045ustar00rootroot00000000000000django-model-utils-4.2.0/model_utils/locale/cs/000077500000000000000000000000001413076733600214115ustar00rootroot00000000000000django-model-utils-4.2.0/model_utils/locale/cs/LC_MESSAGES/000077500000000000000000000000001413076733600231765ustar00rootroot00000000000000django-model-utils-4.2.0/model_utils/locale/cs/LC_MESSAGES/django.mo000066400000000000000000000013011413076733600247700ustar00rootroot00000000000000T    createdendmodifiedstartstatusstatus changedProject-Id-Version: django-model-utils Report-Msgid-Bugs-To: POT-Creation-Date: 2018-05-04 13:40+0200 PO-Revision-Date: 2018-05-04 13:46+0200 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; Last-Translator: Václav Dohnal Language-Team: X-Generator: Poedit 2.0.7 vytvořenokonecupravenozačátekstavzměna stavudjango-model-utils-4.2.0/model_utils/locale/cs/LC_MESSAGES/django.po000066400000000000000000000020601413076733600247760ustar00rootroot00000000000000# 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: https://github.com/jazzband/django-model-utils/issues\n" "POT-Creation-Date: 2018-05-04 13:40+0200\n" "PO-Revision-Date: 2018-05-04 13:46+0200\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" "Last-Translator: Václav Dohnal \n" "Language-Team: N/A\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:37 msgid "start" msgstr "začátek" #: .\models.py:38 msgid "end" msgstr "konec" #: .\models.py:53 msgid "status" msgstr "stav" #: .\models.py:54 msgid "status changed" msgstr "změna stavu" django-model-utils-4.2.0/model_utils/locale/de/000077500000000000000000000000001413076733600213745ustar00rootroot00000000000000django-model-utils-4.2.0/model_utils/locale/de/LC_MESSAGES/000077500000000000000000000000001413076733600231615ustar00rootroot00000000000000django-model-utils-4.2.0/model_utils/locale/de/LC_MESSAGES/django.mo000066400000000000000000000013701413076733600247610ustar00rootroot00000000000000 l  #*n9    activecreateddeletedendmodifiedon holdstartstatusstatus changedProject-Id-Version: django-model-utils Report-Msgid-Bugs-To: POT-Creation-Date: 2015-07-20 10:17-0600 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); aktiverstelltgelöschtEndebearbeitetwartendBeginnStatusStatus geändertdjango-model-utils-4.2.0/model_utils/locale/de/LC_MESSAGES/django.po000066400000000000000000000022371413076733600247670ustar00rootroot00000000000000# 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: 2015-07-20 10:17-0600\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:20 msgid "created" msgstr "erstellt" #: models.py:21 msgid "modified" msgstr "bearbeitet" #: models.py:33 msgid "start" msgstr "Beginn" #: models.py:34 msgid "end" msgstr "Ende" #: models.py:49 msgid "status" msgstr "Status" #: models.py:50 msgid "status changed" msgstr "Status geändert" #: tests/models.py:106 tests/models.py:115 tests/models.py:124 msgid "active" msgstr "aktiv" #: tests/models.py:107 tests/models.py:116 tests/models.py:125 msgid "deleted" msgstr "gelöscht" #: tests/models.py:108 tests/models.py:117 tests/models.py:126 msgid "on hold" msgstr "wartend" django-model-utils-4.2.0/model_utils/locale/fa/000077500000000000000000000000001413076733600213725ustar00rootroot00000000000000django-model-utils-4.2.0/model_utils/locale/fa/LC_MESSAGES/000077500000000000000000000000001413076733600231575ustar00rootroot00000000000000django-model-utils-4.2.0/model_utils/locale/fa/LC_MESSAGES/django.mo000066400000000000000000000012101413076733600247500ustar00rootroot00000000000000T 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); ایجاد شدپایاناصلاح شدشروعوضعیتوضعیت تغییر کردdjango-model-utils-4.2.0/model_utils/locale/fa/LC_MESSAGES/django.po000066400000000000000000000016261413076733600247660ustar00rootroot00000000000000# 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: 2020-09-19 13:00+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:28 msgid "created" msgstr "ایجاد شد" #: models.py:29 msgid "modified" msgstr "اصلاح شد" #: models.py:51 msgid "start" msgstr "شروع" #: models.py:52 msgid "end" msgstr "پایان" #: models.py:67 msgid "status" msgstr "وضعیت" #: models.py:68 msgid "status changed" msgstr "وضعیت تغییر کرد" django-model-utils-4.2.0/model_utils/locale/ru/000077500000000000000000000000001413076733600214325ustar00rootroot00000000000000django-model-utils-4.2.0/model_utils/locale/ru/LC_MESSAGES/000077500000000000000000000000001413076733600232175ustar00rootroot00000000000000django-model-utils-4.2.0/model_utils/locale/ru/LC_MESSAGES/django.mo000066400000000000000000000015101413076733600250130ustar00rootroot00000000000000T    ,createdendmodifiedstartstatusstatus changedProject-Id-Version: django-model-utils Report-Msgid-Bugs-To: POT-Creation-Date: 2017-05-22 19:46+0300 PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE 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); созданоконецизмененоначалостатусстатус измененdjango-model-utils-4.2.0/model_utils/locale/ru/LC_MESSAGES/django.po000066400000000000000000000020761413076733600250260ustar00rootroot00000000000000# 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: 2017-05-22 19:46+0300\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:37 msgid "start" msgstr "начало" #: models.py:38 msgid "end" msgstr "конец" #: models.py:53 msgid "status" msgstr "статус" #: models.py:54 msgid "status changed" msgstr "статус изменен" django-model-utils-4.2.0/model_utils/locale/zh_Hans/000077500000000000000000000000001413076733600223765ustar00rootroot00000000000000django-model-utils-4.2.0/model_utils/locale/zh_Hans/LC_MESSAGES/000077500000000000000000000000001413076733600241635ustar00rootroot00000000000000django-model-utils-4.2.0/model_utils/locale/zh_Hans/LC_MESSAGES/django.mo000066400000000000000000000012311413076733600257570ustar00rootroot00000000000000T ` K X e rcreatedendmodifiedstartstatusstatus changedProject-Id-Version: PACKAGE VERSION Report-Msgid-Bugs-To: POT-Creation-Date: 2018-10-23 15:12+0800 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; 创建时间结束时间修改时间开始时间状态状态修改时间django-model-utils-4.2.0/model_utils/locale/zh_Hans/LC_MESSAGES/django.po000066400000000000000000000015761413076733600257760ustar00rootroot00000000000000# 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: 2018-10-23 15:12+0800\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:37 msgid "start" msgstr "开始时间" #: models.py:38 msgid "end" msgstr "结束时间" #: models.py:53 msgid "status" msgstr "状态" #: models.py:54 msgid "status changed" msgstr "状态修改时间" django-model-utils-4.2.0/model_utils/managers.py000066400000000000000000000332551413076733600217240ustar00rootroot00000000000000import warnings 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 class InheritanceIterable(ModelIterable): def __iter__(self): queryset = self.queryset iter = ModelIterable(queryset) if getattr(queryset, 'subclasses', False): 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 getattr(queryset, '_annotated', False): 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 class InheritanceQuerySetMixin: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._iterable_class = InheritanceIterable def select_subclasses(self, *subclasses): levels = None calculated_subclasses = self._get_subclasses_recurse( self.model, levels=levels) # if none were passed in, we can just short circuit and select all if not subclasses: subclasses = calculated_subclasses else: verified_subclasses = [] 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 self.model: continue if not isinstance(subclass, (str,)): subclass = self._get_ancestors_path( subclass, levels=levels) 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)) ) subclasses = verified_subclasses # workaround https://code.djangoproject.com/ticket/16855 previous_select_related = self.query.select_related if subclasses: new_qs = self.select_related(*subclasses) else: new_qs = self previous_is_dict = isinstance(previous_select_related, dict) new_is_dict = isinstance(new_qs.query.select_related, dict) if previous_is_dict and new_is_dict: new_qs.query.select_related.update(previous_select_related) new_qs.subclasses = subclasses return new_qs def _chain(self, **kwargs): update = {} for name in ['subclasses', '_annotated']: if hasattr(self, name): update[name] = getattr(self, name) chained = super()._chain(**kwargs) chained.__dict__.update(update) return chained def _clone(self, klass=None, setup=False, **kwargs): qs = super()._clone() for name in ['subclasses', '_annotated']: if hasattr(self, name): setattr(qs, name, getattr(self, name)) return qs def annotate(self, *args, **kwargs): qset = super().annotate(*args, **kwargs) qset._annotated = [a.default_alias for a in args] + list(kwargs.keys()) return qset def _get_subclasses_recurse(self, model, levels=None): """ 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 = [] if levels: levels -= 1 for rel in rels: if levels or levels is None: for subclass in self._get_subclasses_recurse( rel.field.model, levels=levels): subclasses.append( rel.get_accessor_name() + LOOKUP_SEP + subclass) subclasses.append(rel.get_accessor_name()) return subclasses def _get_ancestors_path(self, model, levels=None): """ 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( "{!r} is not a subclass of {!r}".format(model, self.model)) ancestry = [] # should be a OneToOneField or None parent_link = model._meta.get_ancestor_link(self.model) if levels: levels -= 1 while parent_link is not None: related = parent_link.remote_field ancestry.insert(0, related.get_accessor_name()) if levels or levels is None: parent_model = related.model parent_link = parent_model._meta.get_ancestor_link( self.model) else: parent_link = None return LOOKUP_SEP.join(ancestry) def _get_sub_obj_recurse(self, obj, s): 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, **kwargs): return self.select_subclasses().get(*args, **kwargs) class InheritanceQuerySet(InheritanceQuerySetMixin, QuerySet): def instance_of(self, *models): """ Fetch only objects that are instances of the provided model(s). """ # If we aren't already selecting the subclasess, 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.attname, # Should this be something else? ) for field in model._meta.parents.values() ]) + ')') return self.select_subclasses(*models).extra(where=[' OR '.join(where_queries)]) class InheritanceManagerMixin: _queryset_class = InheritanceQuerySet def get_queryset(self): return self._queryset_class(self.model) def select_subclasses(self, *subclasses): return self.get_queryset().select_subclasses(*subclasses) def get_subclass(self, *args, **kwargs): return self.get_queryset().get_subclass(*args, **kwargs) def instance_of(self, *models): return self.get_queryset().instance_of(*models) class InheritanceManager(InheritanceManagerMixin, models.Manager): pass class QueryManagerMixin: def __init__(self, *args, **kwargs): if args: self._q = args[0] else: self._q = models.Q(**kwargs) self._order_by = None super().__init__() def order_by(self, *args): self._order_by = args return self def get_queryset(self): qs = super().get_queryset().filter(self._q) if self._order_by is not None: return qs.order_by(*self._order_by) return qs class QueryManager(QueryManagerMixin, models.Manager): pass class SoftDeletableQuerySetMixin: """ QuerySet for SoftDeletableModel. Instead of removing instance sets its ``is_removed`` field to True. """ def delete(self): """ Soft delete objects from queryset (set their ``is_removed`` field to True) """ self.update(is_removed=True) class SoftDeletableQuerySet(SoftDeletableQuerySetMixin, QuerySet): pass class SoftDeletableManagerMixin: """ Manager that limits the queryset by default to show only not removed instances of model. """ _queryset_class = SoftDeletableQuerySet def __init__(self, *args, _emit_deprecation_warnings=False, **kwargs): self.emit_deprecation_warnings = _emit_deprecation_warnings super().__init__(*args, **kwargs) def get_queryset(self): """ Return queryset limited to not removed entries. """ 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(self.model.__class__.__name__) warnings.warn(warning_message, DeprecationWarning) kwargs = {'model': self.model, 'using': self._db} if hasattr(self, '_hints'): kwargs['hints'] = self._hints return self._queryset_class(**kwargs).filter(is_removed=False) class SoftDeletableManager(SoftDeletableManagerMixin, models.Manager): pass class JoinQueryset(models.QuerySet): def get_quoted_query(self, query): query, params = query.sql_with_params() # Put additional quotes around string. params = [ '\'{}\''.format(p) if isinstance(p, str) else p for p in params ] # Cast list of parameters to tuple because I got # "not enough format characters" otherwise. params = tuple(params) return query % params def join(self, qs=None): ''' 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 querset 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: fk = [ fk for fk in qs.model._meta.fields if getattr(fk, 'related_model', None) == self.model ] fk = fk[0] if fk else None model_set = '{}_set'.format(self.model.__name__.lower()) 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.objects.all() TABLE_NAME = 'temp_stuff' query = self.get_quoted_query(qs.query) 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) 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 class JoinManagerMixin: """ Manager that adds a method join. This method allows you to join two querysets together. """ _queryset_class = JoinQueryset def get_queryset(self): return self._queryset_class(model=self.model, using=self._db) class JoinManager(JoinManagerMixin, models.Manager): pass django-model-utils-4.2.0/model_utils/models.py000066400000000000000000000164651413076733600214160ustar00rootroot00000000000000from django.core.exceptions import ImproperlyConfigured from django.db import models, router, transaction from django.db.models.functions import Now from django.db.models.signals import post_save, pre_save 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 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, **kwargs): """ 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, **kwargs): """ 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, **kwargs): """ Add a Querymanager for each status item dynamically. """ if not issubclass(sender, StatusModel): return default_manager = sender._meta.default_manager 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, **kwargs): """ 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, field_name): 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 = SoftDeletableManager(_emit_deprecation_warnings=True) available_objects = SoftDeletableManager() all_objects = models.Manager() def delete(self, using=None, soft=True, *args, **kwargs): """ 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) else: return super().delete(using=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 class SaveSignalHandlingModel(models.Model): """ An abstract base class model to pass a parameter ``signals_to_disable`` to ``save`` method in order to disable signals """ class Meta: abstract = True def save(self, signals_to_disable=None, *args, **kwargs): """ Add an extra parameters to hold which signals to disable If empty, nothing will change """ self.signals_to_disable = signals_to_disable or [] super().save(*args, **kwargs) def save_base(self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None): """ Copied from base class for a minor change. This is an ugly overwriting but since Django's ``save_base`` method does not differ between versions 1.8 and 1.10, that way of implementing wouldn't harm the flow """ using = using or router.db_for_write(self.__class__, instance=self) assert not (force_insert and (force_update or update_fields)) assert update_fields is None or len(update_fields) > 0 cls = origin = self.__class__ if cls._meta.proxy: cls = cls._meta.concrete_model meta = cls._meta if not meta.auto_created and 'pre_save' not in self.signals_to_disable: pre_save.send( sender=origin, instance=self, raw=raw, using=using, update_fields=update_fields, ) with transaction.atomic(using=using, savepoint=False): if not raw: self._save_parents(cls, using, update_fields) updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) self._state.db = using self._state.adding = False if not meta.auto_created and 'post_save' not in self.signals_to_disable: post_save.send( sender=origin, instance=self, created=(not updated), update_fields=update_fields, raw=raw, using=using, ) # Empty the signals in case it might be used somewhere else in future self.signals_to_disable = [] django-model-utils-4.2.0/model_utils/tracker.py000066400000000000000000000350261413076733600215600ustar00rootroot00000000000000from copy import deepcopy from functools import wraps from django.core.exceptions import FieldError from django.db import models from django.db.models.fields.files import FieldFile, FileDescriptor from django.db.models.query_utils import DeferredAttribute 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): """ 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): """ Use our lightweight class to avoid copying the instance on a FieldFile deepcopy. """ if isinstance(value, FieldFile): value = LightStateFieldFile( instance=value.instance, field=value.field, name=value.name, ) return deepcopy(value) class DescriptorMixin: tracker_instance = None def __get__(self, instance, owner): if instance is None: return self was_deferred = False field_name = self._get_field_name() if field_name in instance._deferred_fields: instance._deferred_fields.remove(field_name) was_deferred = True value = super().__get__(instance, owner) if was_deferred: self.tracker_instance.saved_data[field_name] = lightweight_deepcopy(value) return value def _get_field_name(self): return self.field_name class DescriptorWrapper: def __init__(self, field_name, descriptor, tracker_attname): self.field_name = field_name self.descriptor = descriptor self.tracker_attname = tracker_attname def __get__(self, instance, owner): if instance is None: return self was_deferred = self.field_name in instance.get_deferred_fields() try: value = self.descriptor.__get__(instance, owner) except AttributeError: value = self.descriptor 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, value): 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 @staticmethod def cls_for_descriptor(descriptor): if hasattr(descriptor, '__delete__'): return FullDescriptorWrapper else: return DescriptorWrapper class FullDescriptorWrapper(DescriptorWrapper): """ Wrapper for descriptors with all three descriptor methods. """ def __delete__(self, obj): 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, *fields, state=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): """ 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, exc_val, exc_tb): """ 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, fields, field_map): self.instance = instance self.fields = fields self.field_map = field_map self.context = FieldsContext(self, *self.fields) def __enter__(self): return self.context.__enter__() def __exit__(self, exc_type, exc_val, exc_tb): return self.context.__exit__(exc_type, exc_val, exc_tb) def __call__(self, *fields): return FieldsContext(self, *fields, state=self.context.state) @property def deferred_fields(self): return self.instance.get_deferred_fields() def get_field_value(self, field): return getattr(self.instance, self.field_map[field]) def set_saved_fields(self, fields=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=None): """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): """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 return self.previous(field) != self.get_field_value(field) else: raise FieldError('field "%s" not tracked' % field) def previous(self, field): """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): """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) } def init_deferred_fields(self): self.instance._deferred_fields = set() if hasattr(self.instance, '_deferred') and not self.instance._deferred: return class DeferredAttributeTracker(DescriptorMixin, DeferredAttribute): tracker_instance = self class FileDescriptorTracker(DescriptorMixin, FileDescriptor): tracker_instance = self def _get_field_name(self): return self.field.name self.instance._deferred_fields = self.instance.get_deferred_fields() for field in self.instance._deferred_fields: field_obj = self.instance.__class__.__dict__.get(field) if isinstance(field_obj, FileDescriptor): field_tracker = FileDescriptorTracker(field_obj.field) setattr(self.instance.__class__, field, field_tracker) else: field_tracker = DeferredAttributeTracker(field) setattr(self.instance.__class__, field, field_tracker) class FieldTracker: tracker_class = FieldInstanceTracker def __init__(self, fields=None): self.fields = fields def __call__(self, func=None, fields=None): def decorator(f): @wraps(f) def inner(obj, *args, **kwargs): 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): """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, name): self.name = name self.attname = '_%s' % name models.signals.class_prepared.connect(self.finalize_class, sender=cls) def finalize_class(self, sender, **kwargs): if self.fields is None: self.fields = (field.attname for field in sender._meta.fields) self.fields = set(self.fields) for field_name in self.fields: descriptor = 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) models.signals.post_init.connect(self.initialize_tracker) self.model_class = sender setattr(sender, self.name, self) self.patch_save(sender) def initialize_tracker(self, sender, instance, **kwargs): 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() instance._instance_initialized = True def patch_save(self, model): self._patch(model, 'save_base', 'update_fields') self._patch(model, 'refresh_from_db', 'fields') def _patch(self, model, method, fields_kwarg): original = getattr(model, method) @wraps(original) def inner(instance, *args, **kwargs): update_fields = 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) def __get__(self, instance, owner): if instance is None: return self else: return getattr(instance, self.attname) class ModelInstanceTracker(FieldInstanceTracker): def has_changed(self, field): """Returns ``True`` if field has changed from currently saved value""" if not self.instance.pk: return True elif field in self.saved_data: return self.previous(field) != self.get_field_value(field) else: raise FieldError('field "%s" not tracked' % field) def changed(self): """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): return {field: field for field in self.fields} django-model-utils-4.2.0/requirements-test.txt000066400000000000000000000001161413076733600214640ustar00rootroot00000000000000pytest==6.2.5 pytest-django==3.10.0 psycopg2-binary==2.8.6 pytest-cov==2.10.1 django-model-utils-4.2.0/requirements.txt000066400000000000000000000001211413076733600205030ustar00rootroot00000000000000# Dependencies for development of django-model-utils tox sphinx twine freezegun django-model-utils-4.2.0/setup.cfg000066400000000000000000000002641413076733600170500ustar00rootroot00000000000000[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 django-model-utils-4.2.0/setup.py000066400000000000000000000035631413076733600167460ustar00rootroot00000000000000import 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, mode='r') 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*']), install_requires=['Django>=2.0.1'], 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.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Framework :: Django', 'Framework :: Django :: 2.2', 'Framework :: Django :: 3.1', 'Framework :: Django :: 3.2', ], zip_safe=False, tests_require=['Django>=2.2'], package_data={ 'model_utils': [ 'locale/*/LC_MESSAGES/django.po', 'locale/*/LC_MESSAGES/django.mo' ], }, ) django-model-utils-4.2.0/tests/000077500000000000000000000000001413076733600163675ustar00rootroot00000000000000django-model-utils-4.2.0/tests/__init__.py000066400000000000000000000000001413076733600204660ustar00rootroot00000000000000django-model-utils-4.2.0/tests/fields.py000066400000000000000000000014141413076733600202070ustar00rootroot00000000000000from django.db import models def mutable_from_db(value): 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): 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): return mutable_from_db(value) def from_db_value(self, value, expression, connection): return mutable_from_db(value) def get_db_prep_save(self, value, connection): value = super().get_db_prep_save(value, connection) return mutable_to_db(value) django-model-utils-4.2.0/tests/managers.py000066400000000000000000000005671413076733600205460ustar00rootroot00000000000000from model_utils.managers import SoftDeletableManager, SoftDeletableQuerySet class CustomSoftDeleteQuerySet(SoftDeletableQuerySet): def only_read(self): return self.filter(is_read=True) class CustomSoftDeleteManager(SoftDeletableManager): _queryset_class = CustomSoftDeleteQuerySet def only_read(self): return self.get_queryset().only_read() django-model-utils-4.2.0/tests/models.py000066400000000000000000000302411413076733600202240ustar00rootroot00000000000000import django from django.db import models from django.db.models import Manager 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, JoinManagerMixin, QueryManager from model_utils.models import ( SaveSignalHandlingModel, SoftDeletableModel, StatusModel, TimeFramedModel, TimeStampedModel, UUIDModel, ) from model_utils.tracker import FieldTracker, ModelTracker from tests.fields import MutableField from tests.managers import CustomSoftDeleteManager 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 = InheritanceManager() def __str__(self): 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 = 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 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") 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( ("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 AbstractStatusCustomManager(StatusModel): STATUS = Choices( ("first_choice", _("First choice")), ("second_choice", _("Second choice")), ) objects = StatusCustomManager() class Meta: abstract = True class StatusCustomManager(AbstractStatusCustomManager): 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 = QueryManager(published=True) public_confirmed = QueryManager( models.Q(published=True) & models.Q(confirmed=True)) public_reversed = 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 NoRendered(models.Model): """ Test that the no_excerpt_field keyword arg works. This arg should never be used except by the South model-freezing. """ body = SplitField(no_excerpt_field=True) class AuthorMixin: def by_author(self, name): return self.filter(author=name) class PublishedMixin: def published(self): return self.filter(published=True) def unpublished(self): return self.filter(published=False) class ByAuthorQuerySet(models.query.QuerySet, AuthorMixin): pass class FeaturedManager(models.Manager): def get_queryset(self): kwargs = {} if hasattr(self, "_db"): kwargs["using"] = self._db return ByAuthorQuerySet(self.model, **kwargs).filter(feature=True) class AbstractTracked(models.Model): number = 1 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, **kwargs): """ 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, **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) 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 = FieldTracker() 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): 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 = models.Manager() class CustomSoftDelete(SoftDeletableModel): is_read = models.BooleanField(default=False) objects = CustomSoftDeleteManager() class StringyDescriptor: """ Descriptor that returns a string version of the underlying integer value. """ def __init__(self, name): self.name = name def __get__(self, obj, cls=None): 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. if django.VERSION < (3, 0): DeferredAttribute(field_name=self.name).__get__(obj, cls) else: # Since Django 3.0, DeferredAttribute wants a field argument. 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, value): obj.__dict__[self.name] = int(value) def __delete__(self, obj): del obj.__dict__[self.name] class CustomDescriptorField(models.IntegerField): def contribute_to_class(self, cls, name, **kwargs): super().contribute_to_class(cls, name, **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 JoinManager(JoinManagerMixin, models.Manager): pass class BoxJoinModel(models.Model): name = models.CharField(max_length=32) objects = JoinManager() class JoinItemForeignKey(models.Model): weight = models.IntegerField() belonging = models.ForeignKey( BoxJoinModel, null=True, on_delete=models.CASCADE ) objects = JoinManager() class CustomUUIDModel(UUIDModel): pass class CustomNotPrimaryUUIDModel(models.Model): uuid = UUIDField(primary_key=False) class SaveSignalHandlingTestModel(SaveSignalHandlingModel): name = models.CharField(max_length=20) class TimeStampWithStatusModel(TimeStampedModel, StatusModel): STATUS = Choices( ("active", _("active")), ("deleted", _("deleted")), ("on_hold", _("on hold")), ) test_field = models.PositiveSmallIntegerField(default=0) django-model-utils-4.2.0/tests/settings.py000066400000000000000000000011441413076733600206010ustar00rootroot00000000000000import os INSTALLED_APPS = ( 'model_utils', 'tests', ) DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": os.environ.get("DB_NAME", "modelutils"), "USER": os.environ.get("DB_USER", 'postgres'), "PASSWORD": os.environ.get("DB_PASSWORD", ""), "HOST": os.environ.get("DB_HOST", "localhost"), "PORT": os.environ.get("DB_PORT", 5432) }, } SECRET_KEY = 'dummy' CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' django-model-utils-4.2.0/tests/signals.py000066400000000000000000000002611413076733600204000ustar00rootroot00000000000000def pre_save_test(instance, *args, **kwargs): instance.pre_save_runned = True def post_save_test(instance, created, *args, **kwargs): instance.post_save_runned = True django-model-utils-4.2.0/tests/test_choices.py000066400000000000000000000216021413076733600214160ustar00rootroot00000000000000from django.test import TestCase from model_utils import Choices class ChoicesTests(TestCase): def setUp(self): self.STATUS = Choices('DRAFT', 'PUBLISHED') def test_getattr(self): self.assertEqual(self.STATUS.DRAFT, 'DRAFT') def test_indexing(self): self.assertEqual(self.STATUS['PUBLISHED'], 'PUBLISHED') def test_iteration(self): self.assertEqual(tuple(self.STATUS), (('DRAFT', 'DRAFT'), ('PUBLISHED', 'PUBLISHED'))) def test_reversed(self): self.assertEqual(tuple(reversed(self.STATUS)), (('PUBLISHED', 'PUBLISHED'), ('DRAFT', 'DRAFT'))) def test_len(self): self.assertEqual(len(self.STATUS), 2) def test_repr(self): self.assertEqual(repr(self.STATUS), "Choices" + repr(( ('DRAFT', 'DRAFT', 'DRAFT'), ('PUBLISHED', 'PUBLISHED', 'PUBLISHED'), ))) def test_wrong_length_tuple(self): with self.assertRaises(ValueError): Choices(('a',)) def test_contains_value(self): self.assertTrue('PUBLISHED' in self.STATUS) self.assertTrue('DRAFT' in self.STATUS) def test_doesnt_contain_value(self): self.assertFalse('UNPUBLISHED' in self.STATUS) def test_deepcopy(self): import copy self.assertEqual(list(self.STATUS), list(copy.deepcopy(self.STATUS))) def test_equality(self): self.assertEqual(self.STATUS, Choices('DRAFT', 'PUBLISHED')) def test_inequality(self): self.assertNotEqual(self.STATUS, ['DRAFT', 'PUBLISHED']) self.assertNotEqual(self.STATUS, Choices('DRAFT')) def test_composability(self): self.assertEqual(Choices('DRAFT') + Choices('PUBLISHED'), self.STATUS) self.assertEqual(Choices('DRAFT') + ('PUBLISHED',), self.STATUS) self.assertEqual(('DRAFT',) + Choices('PUBLISHED'), self.STATUS) def test_option_groups(self): c = Choices(('group a', ['one', 'two']), ['group b', ('three',)]) self.assertEqual( list(c), [ ('group a', [('one', 'one'), ('two', 'two')]), ('group b', [('three', 'three')]), ], ) class LabelChoicesTests(ChoicesTests): def setUp(self): self.STATUS = Choices( ('DRAFT', 'is draft'), ('PUBLISHED', 'is published'), 'DELETED', ) def test_iteration(self): self.assertEqual(tuple(self.STATUS), ( ('DRAFT', 'is draft'), ('PUBLISHED', 'is published'), ('DELETED', 'DELETED'), )) def test_reversed(self): self.assertEqual(tuple(reversed(self.STATUS)), ( ('DELETED', 'DELETED'), ('PUBLISHED', 'is published'), ('DRAFT', 'is draft'), )) def test_indexing(self): self.assertEqual(self.STATUS['PUBLISHED'], 'is published') def test_default(self): self.assertEqual(self.STATUS.DELETED, 'DELETED') def test_provided(self): self.assertEqual(self.STATUS.DRAFT, 'DRAFT') def test_len(self): self.assertEqual(len(self.STATUS), 3) def test_equality(self): self.assertEqual(self.STATUS, Choices( ('DRAFT', 'is draft'), ('PUBLISHED', 'is published'), 'DELETED', )) def test_inequality(self): self.assertNotEqual(self.STATUS, [ ('DRAFT', 'is draft'), ('PUBLISHED', 'is published'), 'DELETED' ]) self.assertNotEqual(self.STATUS, Choices('DRAFT')) def test_repr(self): self.assertEqual(repr(self.STATUS), "Choices" + repr(( ('DRAFT', 'DRAFT', 'is draft'), ('PUBLISHED', 'PUBLISHED', 'is published'), ('DELETED', 'DELETED', 'DELETED'), ))) def test_contains_value(self): 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): self.assertFalse('UNPUBLISHED' in self.STATUS) def test_doesnt_contain_display_value(self): self.assertFalse('is draft' in self.STATUS) def test_composability(self): 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): 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(ChoicesTests): def setUp(self): self.STATUS = Choices( (0, 'DRAFT', 'is draft'), (1, 'PUBLISHED', 'is published'), (2, 'DELETED', 'is deleted')) def test_iteration(self): self.assertEqual(tuple(self.STATUS), ( (0, 'is draft'), (1, 'is published'), (2, 'is deleted'), )) def test_reversed(self): self.assertEqual(tuple(reversed(self.STATUS)), ( (2, 'is deleted'), (1, 'is published'), (0, 'is draft'), )) def test_indexing(self): self.assertEqual(self.STATUS[1], 'is published') def test_getattr(self): self.assertEqual(self.STATUS.DRAFT, 0) def test_len(self): self.assertEqual(len(self.STATUS), 3) def test_repr(self): self.assertEqual(repr(self.STATUS), "Choices" + repr(( (0, 'DRAFT', 'is draft'), (1, 'PUBLISHED', 'is published'), (2, 'DELETED', 'is deleted'), ))) def test_contains_value(self): self.assertTrue(0 in self.STATUS) self.assertTrue(1 in self.STATUS) self.assertTrue(2 in self.STATUS) def test_doesnt_contain_value(self): self.assertFalse(3 in self.STATUS) def test_doesnt_contain_display_value(self): self.assertFalse('is draft' in self.STATUS) def test_doesnt_contain_python_attr(self): self.assertFalse('PUBLISHED' in self.STATUS) def test_equality(self): self.assertEqual(self.STATUS, Choices( (0, 'DRAFT', 'is draft'), (1, 'PUBLISHED', 'is published'), (2, 'DELETED', 'is deleted') )) def test_inequality(self): 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): 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): 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): self.choices = Choices( (0, 'a', 'A'), (1, 'b', 'B'), ) def test_nonexistent_identifiers_raise(self): with self.assertRaises(ValueError): self.choices.subset('a', 'c') def test_solo_nonexistent_identifiers_raise(self): with self.assertRaises(ValueError): self.choices.subset('c') def test_empty_subset_passes(self): subset = self.choices.subset() self.assertEqual(subset, Choices()) def test_subset_returns_correct_subset(self): subset = self.choices.subset('a') self.assertEqual(subset, Choices((0, 'a', 'A'))) django-model-utils-4.2.0/tests/test_fields/000077500000000000000000000000001413076733600206745ustar00rootroot00000000000000django-model-utils-4.2.0/tests/test_fields/__init__.py000066400000000000000000000000001413076733600227730ustar00rootroot00000000000000django-model-utils-4.2.0/tests/test_fields/test_field_tracker.py000066400000000000000000001026501413076733600251070ustar00rootroot00000000000000from unittest import skip from django.core.cache import cache from django.core.exceptions import FieldError from django.db.models.fields.files import FieldFile from django.test import TestCase from model_utils import FieldTracker from model_utils.tracker import DescriptorWrapper from tests.models import ( InheritedModelTracked, InheritedTracked, InheritedTrackedFK, ModelTracked, ModelTrackedFK, ModelTrackedMultiple, ModelTrackedNotDefault, Tracked, TrackedAbstract, TrackedFileField, TrackedFK, TrackedMultiple, TrackedNonFieldAttr, TrackedNotDefault, TrackerTimeStamped, ) class FieldTrackerTestCase(TestCase): tracker = None def assertHasChanged(self, **kwargs): tracker = kwargs.pop('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, **kwargs): tracker = kwargs.pop('tracker', self.tracker) for field, value in kwargs.items(): self.assertEqual(tracker.previous(field), value) def assertChanged(self, **kwargs): tracker = kwargs.pop('tracker', self.tracker) self.assertEqual(tracker.changed(), kwargs) def assertCurrent(self, **kwargs): tracker = kwargs.pop('tracker', self.tracker) self.assertEqual(tracker.current(), kwargs) def update_instance(self, **kwargs): for field, value in kwargs.items(): setattr(self.instance, field, value) self.instance.save() class FieldTrackerCommonTests: def test_pre_save_previous(self): self.assertPrevious(name=None, number=None) self.instance.name = 'new age' self.instance.number = 8 self.assertPrevious(name=None, number=None) class FieldTrackerTests(FieldTrackerTestCase, FieldTrackerCommonTests): tracked_class = Tracked def setUp(self): self.instance = self.tracked_class() self.tracker = self.instance.tracker def test_descriptor(self): self.assertTrue(isinstance(self.tracked_class.tracker, FieldTracker)) def test_pre_save_changed(self): 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): 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): self.instance.number = 1 self.instance.save(False, False, None, None) self.assertChanged() def test_first_save(self): 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): 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): 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): 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): 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): 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): 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): self.instance.name = 'new age' self.instance.number = 1 self.instance.save() item = self.tracked_class.objects.only('name').first() 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() 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() 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): 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(FieldTrackerTestCase, FieldTrackerCommonTests): tracked_class = TrackedNotDefault def setUp(self): self.instance = self.tracked_class() self.tracker = self.instance.name_tracker def test_pre_save_changed(self): 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): 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): 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): 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): self.update_instance(name='retro', number=4) self.instance.name = 'new age' self.assertPrevious(name='retro', number=None) def test_post_save_changed(self): 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): 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): 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(FieldTrackerTestCase): tracked_class = TrackedNonFieldAttr def setUp(self): self.instance = self.tracked_class() self.tracker = self.instance.tracker def test_previous(self): 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): 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): 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): self.assertCurrent(rounded=None) self.instance.number = 7.5 self.assertCurrent(rounded=8) self.instance.save() self.assertCurrent(rounded=8) class FieldTrackedModelMultiTests(FieldTrackerTestCase, FieldTrackerCommonTests): tracked_class = TrackedMultiple def setUp(self): self.instance = self.tracked_class() self.trackers = [self.instance.name_tracker, self.instance.number_tracker] def test_pre_save_changed(self): 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): 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): for tracker in self.trackers: self.tracker = tracker super().test_pre_save_previous() def test_post_save_has_changed(self): 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): 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): 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): 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 FieldTrackerForeignKeyTests(FieldTrackerTestCase): fk_class = Tracked tracked_class = TrackedFK def setUp(self): self.old_fk = self.fk_class.objects.create(number=8) self.instance = self.tracked_class.objects.create(fk=self.old_fk) def test_default(self): 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) 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): 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) 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): 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) self.assertChanged(fk=self.old_fk.id) self.assertPrevious(fk=self.old_fk.id) self.assertCurrent(fk=self.instance.fk_id) class FieldTrackerTimeStampedTests(FieldTrackerTestCase): fk_class = Tracked tracked_class = TrackerTimeStamped def setUp(self): self.instance = self.tracked_class.objects.create(name='old', number=1) self.tracker = self.instance.tracker def test_set_modified_on_save(self): 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): 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): 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(FieldTrackerTestCase): tracked_class = TrackedFileField def setUp(self): 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): """ 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') self.assertIsNotNone(field_file_copy) 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): self.assertChanged(some_file=None) self.instance.some_file = self.some_file self.assertChanged(some_file=None) def test_pre_save_has_changed(self): self.assertHasChanged(some_file=True) self.instance.some_file = self.some_file self.assertHasChanged(some_file=True) def test_pre_save_previous(self): self.assertPrevious(some_file=None) self.instance.some_file = self.some_file self.assertPrevious(some_file=None) def test_post_save_changed(self): 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): 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): 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): 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 = ModelTracked def test_cache_compatible(self): 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): 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): 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): 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): 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): 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): 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): 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): 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(FieldTrackerForeignKeyTests): fk_class = ModelTracked tracked_class = ModelTrackedFK def test_custom_without_id(self): 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): self.name2 = 'test' self.assertEqual(self.tracker.previous('name2'), None) self.assertTrue(self.tracker.has_changed('name2')) @skip class AbstractModelTrackerTests(ModelTrackerTests): tracked_class = TrackedAbstract class TrackerContextDecoratorTests(TestCase): def setUp(self): self.instance = Tracked.objects.create(number=1) self.tracker = self.instance.tracker def assertChanged(self, *fields): for f in fields: self.assertTrue(self.tracker.has_changed(f)) def assertNotChanged(self, *fields): for f in fields: self.assertFalse(self.tracker.has_changed(f)) def test_context_manager(self): 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): 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): @Tracked.tracker def tracked_method(obj): obj.name = 'new' self.assertChanged('name') tracked_method(self.instance) self.assertNotChanged('name') def test_tracker_decorator_fields(self): @Tracked.tracker(fields=['name']) def tracked_method(obj): 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): with self.tracker: self.instance.name = 'new' self.instance.save() self.assertChanged('name') self.assertNotChanged('name') django-model-utils-4.2.0/tests/test_fields/test_monitor_field.py000066400000000000000000000077401413076733600251470ustar00rootroot00000000000000from datetime import datetime from django.test import TestCase from freezegun import freeze_time from model_utils.fields import MonitorField from tests.models import DoubleMonitored, Monitored, MonitorWhen, MonitorWhenEmpty class MonitorFieldTests(TestCase): def setUp(self): with freeze_time(datetime(2016, 1, 1, 10, 0, 0)): self.instance = Monitored(name='Charlie') self.created = self.instance.name_changed def test_save_no_change(self): self.instance.save() self.assertEqual(self.instance.name_changed, self.created) def test_save_changed(self): with freeze_time(datetime(2016, 1, 1, 12, 0, 0)): self.instance.name = 'Maria' self.instance.save() self.assertEqual(self.instance.name_changed, datetime(2016, 1, 1, 12, 0, 0)) def test_double_save(self): 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): with self.assertRaises(TypeError): MonitorField() class MonitorWhenFieldTests(TestCase): """ Will record changes only when name is 'Jose' or 'Maria' """ def setUp(self): with freeze_time(datetime(2016, 1, 1, 10, 0, 0)): self.instance = MonitorWhen(name='Charlie') self.created = self.instance.name_changed def test_save_no_change(self): self.instance.save() self.assertEqual(self.instance.name_changed, self.created) def test_save_changed_to_Jose(self): with freeze_time(datetime(2016, 1, 1, 12, 0, 0)): self.instance.name = 'Jose' self.instance.save() self.assertEqual(self.instance.name_changed, datetime(2016, 1, 1, 12, 0, 0)) def test_save_changed_to_Maria(self): with freeze_time(datetime(2016, 1, 1, 12, 0, 0)): self.instance.name = 'Maria' self.instance.save() self.assertEqual(self.instance.name_changed, datetime(2016, 1, 1, 12, 0, 0)) def test_save_changed_to_Pedro(self): self.instance.name = 'Pedro' self.instance.save() self.assertEqual(self.instance.name_changed, self.created) def test_double_save(self): 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): self.instance = MonitorWhenEmpty(name='Charlie') self.created = self.instance.name_changed def test_save_no_change(self): self.instance.save() self.assertEqual(self.instance.name_changed, self.created) def test_save_changed_to_Jose(self): self.instance.name = 'Jose' self.instance.save() self.assertEqual(self.instance.name_changed, self.created) def test_save_changed_to_Maria(self): self.instance.name = 'Maria' self.instance.save() self.assertEqual(self.instance.name_changed, self.created) class MonitorDoubleFieldTests(TestCase): def setUp(self): DoubleMonitored.objects.create(name='Charlie', name2='Charlie2') def test_recursion_error_with_only(self): # Any field passed to only() is generating a recursion error list(DoubleMonitored.objects.only('id')) def test_recursion_error_with_defer(self): # 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): obj = DoubleMonitored.objects.defer('name').get(name='Charlie') with freeze_time("2016-12-01"): obj.name = 'Charlie2' obj.save() self.assertEqual(obj.name_changed, datetime(2016, 12, 1)) django-model-utils-4.2.0/tests/test_fields/test_split_field.py000066400000000000000000000046441413076733600246130ustar00rootroot00000000000000from 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): self.post = Article.objects.create( title='example post', body=self.full_text) def test_unicode_content(self): self.assertEqual(str(self.post.body), self.full_text) def test_excerpt(self): self.assertEqual(self.post.body.excerpt, self.excerpt) def test_content(self): self.assertEqual(self.post.body.content, self.full_text) def test_has_more(self): self.assertTrue(self.post.body.has_more) def test_not_has_more(self): 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): 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): 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): 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): with self.assertRaises(AttributeError): self.post.body.excerpt = 'this should fail' def test_access_via_class(self): with self.assertRaises(AttributeError): Article.body def test_none(self): a = Article(title='Some Title', body=None) self.assertEqual(a.body, None) def test_assign_splittext(self): a = Article(title='Some Title') a.body = self.post.body self.assertEqual(a.body.excerpt, 'summary\n') def test_value_to_string(self): f = self.post._meta.get_field('body') self.assertEqual(f.value_to_string(self.post), self.full_text) def test_abstract_inheritance(self): class Child(SplitFieldAbstractParent): pass self.assertEqual( [f.name for f in Child._meta.fields], ["id", "content", "_content_excerpt"]) django-model-utils-4.2.0/tests/test_fields/test_status_field.py000066400000000000000000000017371413076733600250030ustar00rootroot00000000000000from 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): instance = StatusFieldDefaultFilled() self.assertEqual(instance.status, instance.STATUS.yes) def test_status_with_default_not_filled(self): instance = StatusFieldDefaultNotFilled() self.assertEqual(instance.status, instance.STATUS.no) def test_no_check_for_status(self): 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): instance = StatusFieldDefaultFilled() self.assertEqual(instance.get_status_display(), "Yes") def test_choices_name(self): StatusFieldChoicesName() django-model-utils-4.2.0/tests/test_fields/test_urlsafe_token_field.py000066400000000000000000000040711413076733600263130ustar00rootroot00000000000000from 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): field = UrlsafeTokenField() self.assertFalse(field.editable) def test_editable(self): field = UrlsafeTokenField(editable=True) self.assertTrue(field.editable) def test_max_length_default(self): field = UrlsafeTokenField() self.assertEqual(field.max_length, 128) def test_max_length(self): field = UrlsafeTokenField(max_length=256) self.assertEqual(field.max_length, 256) def test_factory_default(self): field = UrlsafeTokenField() self.assertIsNone(field._factory) def test_factory_not_callable(self): with self.assertRaises(TypeError): UrlsafeTokenField(factory='INVALID') def test_get_default(self): field = UrlsafeTokenField() value = field.get_default() self.assertEqual(len(value), field.max_length) def test_get_default_with_non_default_max_length(self): field = UrlsafeTokenField(max_length=64) value = field.get_default() self.assertEqual(len(value), 64) def test_get_default_with_factory(self): 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): field = UrlsafeTokenField(default='DEFAULT') self.assertIs(field.default, NOT_PROVIDED) def test_deconstruct(self): def test_factory(): pass 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) django-model-utils-4.2.0/tests/test_fields/test_uuid_field.py000066400000000000000000000022101413076733600244110ustar00rootroot00000000000000import 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): instance = UUIDField() self.assertEqual(instance.default, uuid.uuid4) def test_uuid_version_1(self): instance = UUIDField(version=1) self.assertEqual(instance.default, uuid.uuid1) def test_uuid_version_2_error(self): self.assertRaises(ValidationError, UUIDField, 'version', 2) def test_uuid_version_3(self): instance = UUIDField(version=3) self.assertEqual(instance.default, uuid.uuid3) def test_uuid_version_4(self): instance = UUIDField(version=4) self.assertEqual(instance.default, uuid.uuid4) def test_uuid_version_5(self): instance = UUIDField(version=5) self.assertEqual(instance.default, uuid.uuid5) def test_uuid_version_bellow_min(self): self.assertRaises(ValidationError, UUIDField, 'version', 0) def test_uuid_version_above_max(self): self.assertRaises(ValidationError, UUIDField, 'version', 6) django-model-utils-4.2.0/tests/test_inheritance_iterable.py000066400000000000000000000010331413076733600241350ustar00rootroot00000000000000from django.db.models import Prefetch from django.test import TestCase from tests.models import InheritanceManagerTestChild1, InheritanceManagerTestParent class InheritanceIterableTest(TestCase): def test_prefetch(self): qs = InheritanceManagerTestChild1.objects.all().prefetch_related( Prefetch( 'normal_field', queryset=InheritanceManagerTestParent.objects.all(), to_attr='normal_field_prefetched' ) ) self.assertEqual(qs.count(), 0) django-model-utils-4.2.0/tests/test_managers/000077500000000000000000000000001413076733600212235ustar00rootroot00000000000000django-model-utils-4.2.0/tests/test_managers/__init__.py000066400000000000000000000000001413076733600233220ustar00rootroot00000000000000django-model-utils-4.2.0/tests/test_managers/test_inheritance_manager.py000066400000000000000000000542501413076733600266250ustar00rootroot00000000000000from django.db import models from django.test import TestCase from tests.models import ( InheritanceManagerTestChild1, InheritanceManagerTestChild2, InheritanceManagerTestChild3, InheritanceManagerTestChild4, InheritanceManagerTestGrandChild1, InheritanceManagerTestGrandChild1_2, InheritanceManagerTestParent, InheritanceManagerTestRelated, TimeFrame, ) class InheritanceManagerTests(TestCase): def setUp(self): 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): return InheritanceManagerTestParent.objects def test_normal(self): 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): 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): """ 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): 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): 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): 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): self.assertEqual( self.get_manager().get_subclass(pk=self.child1.pk), self.child1) def test_get_subclass_on_queryset(self): self.assertEqual( self.get_manager().all().get_subclass(pk=self.child1.pk), self.child1) def test_prior_select_related(self): 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): """ 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 'child4_onetoone', ] self.assertEqual(set(results.subclasses), set(expected_related_names)) def test_manually_specifying_parent_fk_single_subclass(self): """ 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): 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): """ 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): 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): """ 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): """ 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): """ 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, 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): """ 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, 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): """ 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): """ 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): """ 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): """ 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): """ 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): """ 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): """ 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): """ 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): child3 = InheritanceManagerTestChild3.objects.create() results = InheritanceManagerTestParent.objects.instance_of(InheritanceManagerTestChild3) self.assertEqual([child3], list(results)) def test_limit_to_specific_grandchild_class(self): 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): # 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): # 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): 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): 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): child3 = InheritanceManagerTestChild3.objects.create() results = InheritanceManagerTestParent.objects.select_subclasses(InheritanceManagerTestChild1).instance_of(InheritanceManagerTestChild3) self.assertEqual({child3}, set(results)) class InheritanceManagerRelatedTests(InheritanceManagerTests): def setUp(self): 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): return self.related.imtests def test_get_method_with_select_subclasses(self): 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): 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): 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): 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): 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): 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): qs = InheritanceManagerTestParent.objects.select_subclasses() self.assertEqual(qs.subclasses, qs._clone().subclasses) django-model-utils-4.2.0/tests/test_managers/test_join_manager.py000066400000000000000000000024331413076733600252670ustar00rootroot00000000000000from django.test import TestCase from tests.models import BoxJoinModel, JoinItemForeignKey class JoinManagerTest(TestCase): def setUp(self): for i in range(20): BoxJoinModel.objects.create(name='name_{i}'.format(i=i)) JoinItemForeignKey.objects.create( weight=10, belonging=BoxJoinModel.objects.get(name='name_1') ) JoinItemForeignKey.objects.create(weight=20) def test_self_join(self): 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): qs = BoxJoinModel.objects.filter(name='name_1') result = qs.join() self.assertEqual(result.count(), 1) def test_join_with_other_qs(self): 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): 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) django-model-utils-4.2.0/tests/test_managers/test_query_manager.py000066400000000000000000000014521413076733600254750ustar00rootroot00000000000000from django.test import TestCase from tests.models import Post class QueryManagerTests(TestCase): def setUp(self): 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): qs = Post.public.all() self.assertEqual([p.order for p in qs], [0, 1, 4, 5]) def test_passing_Q(self): qs = Post.public_confirmed.all() self.assertEqual([p.order for p in qs], [0, 1]) def test_ordering(self): qs = Post.public_reversed.all() self.assertEqual([p.order for p in qs], [5, 4, 1, 0]) django-model-utils-4.2.0/tests/test_managers/test_softdelete_manager.py000066400000000000000000000016401413076733600264650ustar00rootroot00000000000000from django.test import TestCase from tests.models import CustomSoftDelete class CustomSoftDeleteManagerTests(TestCase): def test_custom_manager_empty(self): qs = CustomSoftDelete.objects.only_read() self.assertEqual(qs.count(), 0) def test_custom_qs_empty(self): qs = CustomSoftDelete.objects.all().only_read() self.assertEqual(qs.count(), 0) def test_is_read(self): for is_read in [True, False, True, False]: CustomSoftDelete.objects.create(is_read=is_read) qs = CustomSoftDelete.objects.only_read() self.assertEqual(qs.count(), 2) def test_is_read_removed(self): for is_read, is_removed in [(True, True), (True, False), (False, False), (False, True)]: CustomSoftDelete.objects.create(is_read=is_read, is_removed=is_removed) qs = CustomSoftDelete.objects.only_read() self.assertEqual(qs.count(), 1) django-model-utils-4.2.0/tests/test_managers/test_status_manager.py000066400000000000000000000013271413076733600256540ustar00rootroot00000000000000from 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): self.assertTrue(isinstance(StatusManagerAdded.active, QueryManager)) def test_conflict_error(self): with self.assertRaises(ImproperlyConfigured): class ErrorModel(StatusModel): STATUS = ( ('active', 'Is Active'), ('deleted', 'Is Deleted'), ) active = models.BooleanField() django-model-utils-4.2.0/tests/test_miscellaneous.py000066400000000000000000000015551413076733600226510ustar00rootroot00000000000000from 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): call_command('makemigrations', dry_run=True) class GetExcerptTests(TestCase): def test_split(self): e = get_excerpt("some content\n\n\n\nsome more") self.assertEqual(e, 'some content\n') def test_auto_split(self): 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): e = get_excerpt("some text\n\nmore text") self.assertEqual(e, 'some text') def test_middle_of_line(self): e = get_excerpt("some text more text") self.assertEqual(e, "some text more text") django-model-utils-4.2.0/tests/test_models/000077500000000000000000000000001413076733600207115ustar00rootroot00000000000000django-model-utils-4.2.0/tests/test_models/__init__.py000066400000000000000000000000001413076733600230100ustar00rootroot00000000000000django-model-utils-4.2.0/tests/test_models/test_deferred_fields.py000066400000000000000000000051221413076733600254300ustar00rootroot00000000000000from django.test import TestCase from tests.models import ModelWithCustomDescriptor class CustomDescriptorTests(TestCase): def setUp(self): 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): 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): 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')) django-model-utils-4.2.0/tests/test_models/test_savesignalhandling_model.py000066400000000000000000000030441413076733600273440ustar00rootroot00000000000000from django.db.models.signals import post_save, pre_save from django.test import TestCase from tests.models import SaveSignalHandlingTestModel from tests.signals import post_save_test, pre_save_test class SaveSignalHandlingModelTests(TestCase): def test_pre_save(self): pre_save.connect(pre_save_test, sender=SaveSignalHandlingTestModel) obj = SaveSignalHandlingTestModel.objects.create(name='Test') delattr(obj, 'pre_save_runned') obj.name = 'Test A' obj.save() self.assertEqual(obj.name, 'Test A') self.assertTrue(hasattr(obj, 'pre_save_runned')) obj = SaveSignalHandlingTestModel.objects.create(name='Test') delattr(obj, 'pre_save_runned') obj.name = 'Test B' obj.save(signals_to_disable=['pre_save']) self.assertEqual(obj.name, 'Test B') self.assertFalse(hasattr(obj, 'pre_save_runned')) def test_post_save(self): post_save.connect(post_save_test, sender=SaveSignalHandlingTestModel) obj = SaveSignalHandlingTestModel.objects.create(name='Test') delattr(obj, 'post_save_runned') obj.name = 'Test A' obj.save() self.assertEqual(obj.name, 'Test A') self.assertTrue(hasattr(obj, 'post_save_runned')) obj = SaveSignalHandlingTestModel.objects.create(name='Test') delattr(obj, 'post_save_runned') obj.name = 'Test B' obj.save(signals_to_disable=['post_save']) self.assertEqual(obj.name, 'Test B') self.assertFalse(hasattr(obj, 'post_save_runned')) django-model-utils-4.2.0/tests/test_models/test_softdeletable_model.py000066400000000000000000000036171413076733600263260ustar00rootroot00000000000000from django.db.utils import ConnectionDoesNotExist from django.test import TestCase from tests.models import SoftDeletable class SoftDeletableModelTests(TestCase): def test_can_only_see_not_removed_entries(self): 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): 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): 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): obj = SoftDeletable.available_objects.create(name='a') self.assertRaises(ConnectionDoesNotExist, obj.delete, using='other') def test_instance_purge(self): 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): instance = SoftDeletable.available_objects.create(name='a') self.assertRaises(ConnectionDoesNotExist, instance.delete, using='other', soft=False) def test_deprecation_warning(self): self.assertWarns(DeprecationWarning, SoftDeletable.objects.all) django-model-utils-4.2.0/tests/test_models/test_status_model.py000066400000000000000000000075551413076733600250410ustar00rootroot00000000000000from datetime import datetime from django.test.testcases import TestCase from freezegun import freeze_time from tests.models import Status, StatusCustomManager, StatusPlainTuple class StatusModelTests(TestCase): def setUp(self): self.model = Status self.on_hold = Status.STATUS.on_hold self.active = Status.STATUS.active def test_created(self): with freeze_time(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): 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): ''' Tests if the save method updated status_changed field accordingly when update_fields is used as an argument and status_changed is provided ''' with freeze_time(datetime(2020, 1, 1)): t1 = Status.objects.create() with freeze_time(datetime(2020, 1, 2)): t1.status = Status.on_hold t1.save(update_fields=['status', 'status_changed']) self.assertEqual(t1.status_changed, datetime(2020, 1, 2)) def test_save_with_update_fields_overrides_status_changed_not_provided(self): ''' 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 freeze_time(datetime(2020, 1, 1)): t1 = Status.objects.create() with freeze_time(datetime(2020, 1, 2)): t1.status = Status.on_hold t1.save(update_fields=['status']) self.assertEqual(t1.status_changed, datetime(2020, 1, 2)) class StatusModelPlainTupleTests(StatusModelTests): def setUp(self): 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): # 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. StatusCustomManager.objects.create(status='first_choice') StatusCustomManager.objects.create(status='second_choice') StatusCustomManager.objects.create(status='second_choice') # ...which made this count() equal to 1 (only 1 element with status='first_choice')... self.assertEqual(StatusCustomManager._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(StatusCustomManager._default_manager.filter(status='second_choice').count(), 2) django-model-utils-4.2.0/tests/test_models/test_timeframed_model.py000066400000000000000000000031231413076733600256160ustar00rootroot00000000000000from 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): self.now = datetime.now() def test_not_yet_begun(self): TimeFrame.objects.create(start=self.now + timedelta(days=2)) self.assertEqual(TimeFrame.timeframed.count(), 0) def test_finished(self): TimeFrame.objects.create(end=self.now - timedelta(days=1)) self.assertEqual(TimeFrame.timeframed.count(), 0) def test_no_end(self): TimeFrame.objects.create(start=self.now - timedelta(days=10)) self.assertEqual(TimeFrame.timeframed.count(), 1) def test_no_start(self): TimeFrame.objects.create(end=self.now + timedelta(days=2)) self.assertEqual(TimeFrame.timeframed.count(), 1) def test_within_range(self): 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): self.assertTrue(isinstance(TimeFrameManagerAdded.timeframed, QueryManager)) def test_conflict_error(self): with self.assertRaises(ImproperlyConfigured): class ErrorModel(TimeFramedModel): timeframed = models.BooleanField() django-model-utils-4.2.0/tests/test_models/test_timestamped_model.py000066400000000000000000000126311413076733600260210ustar00rootroot00000000000000from datetime import datetime, timedelta from django.test import TestCase from freezegun import freeze_time from tests.models import TimeStamp, TimeStampWithStatusModel class TimeStampedModelTests(TestCase): def test_created(self): with freeze_time(datetime(2016, 1, 1)): t1 = TimeStamp.objects.create() self.assertEqual(t1.created, datetime(2016, 1, 1)) def test_created_sets_modified(self): ''' Ensure that on creation that modifed is set exactly equal to created. ''' t1 = TimeStamp.objects.create() self.assertEqual(t1.created, t1.modified) def test_modified(self): with freeze_time(datetime(2016, 1, 1)): t1 = TimeStamp.objects.create() with freeze_time(datetime(2016, 1, 2)): t1.save() self.assertEqual(t1.modified, datetime(2016, 1, 2)) def test_overriding_created_via_object_creation_also_uses_creation_date_for_modified(self): """ Setting the created date when first creating an object should be permissable. """ 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): """ 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): """ 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): """ 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): """ 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): """ 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 freeze_time(datetime(2020, 1, 1)): t1 = TimeStamp.objects.create() with freeze_time(datetime(2020, 1, 2)): t1.save(update_fields=update_fields) self.assertEqual(t1.modified, datetime(2020, 1, 2)) def test_save_is_skipped_for_empty_update_fields_iterable(self): tests = ( [], # list (), # tuple set(), # set ) for update_fields in tests: with self.subTest(update_fields=update_fields): with freeze_time(datetime(2020, 1, 1)): t1 = TimeStamp.objects.create() with freeze_time(datetime(2020, 1, 2)): 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)) def test_save_updates_modified_value_when_update_fields_explicitly_set_to_none(self): with freeze_time(datetime(2020, 1, 1)): t1 = TimeStamp.objects.create() with freeze_time(datetime(2020, 1, 2)): t1.save(update_fields=None) self.assertEqual(t1.modified, datetime(2020, 1, 2)) def test_model_inherit_timestampmodel_and_statusmodel(self): with freeze_time(datetime(2020, 1, 1)): t1 = TimeStampWithStatusModel.objects.create() with freeze_time(datetime(2020, 1, 2)): t1.save(update_fields=['test_field', 'status']) self.assertEqual(t1.modified, datetime(2020, 1, 2)) django-model-utils-4.2.0/tests/test_models/test_uuid_model.py000066400000000000000000000011751413076733600244540ustar00rootroot00000000000000from django.test import TestCase from tests.models import CustomNotPrimaryUUIDModel, CustomUUIDModel class UUIDFieldTests(TestCase): def test_uuid_model_with_uuid_field_as_primary_key(self): 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): instance = CustomNotPrimaryUUIDModel() instance.save() self.assertEqual(instance.uuid.__class__.__name__, 'UUID') self.assertNotEqual(instance.uuid, instance.pk) django-model-utils-4.2.0/tox.ini000066400000000000000000000020311413076733600165340ustar00rootroot00000000000000[tox] envlist = py{36,37,38,39}-dj{22,31,32} py310-dj{31,32} py{38,39,310}-djmain flake8 isort [gh-actions] python = 3.6: py36 3.7: py37 3.8: py38, flake8, isort 3.9: py39 3.10: py310 [testenv] deps = freezegun==0.3.12 -rrequirements-test.txt dj22: Django==2.2.* dj31: Django==3.1.* dj32: Django==3.2.* djmain: https://github.com/django/django/archive/main.tar.gz ignore_outcome = djmain: True ignore_errors = djmain: True passenv = CI GITHUB_* DB_* usedevelop = True commands = pytest {posargs} [testenv:flake8] basepython = python3.8 deps = flake8 skip_install = True commands = flake8 model_utils tests [flake8] ignore = E731 ; do not assign a lambda expression, use a def W503 ; line break before binary operator E402 ; module level import not at top of file E501 ; line too long [testenv:isort] basepython = python3.8 deps = isort commands = isort model_utils tests setup.py --check-only --diff skip_install = True django-model-utils-4.2.0/translations.py000077500000000000000000000015461413076733600203310ustar00rootroot00000000000000#!/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])