pax_global_header00006660000000000000000000000064121317004270014507gustar00rootroot0000000000000052 comment=7bd3bf5f1e7e1384ebbad60ca37a1c2ecc51f7e5 django-model-utils-1.3.1/000077500000000000000000000000001213170042700152075ustar00rootroot00000000000000django-model-utils-1.3.1/.gitignore000066400000000000000000000001271213170042700171770ustar00rootroot00000000000000dist/* django_model_utils.egg-info/* HGREV .coverage .tox/ Django-*.egg *.pyc htmlcov/ django-model-utils-1.3.1/.hgignore000066400000000000000000000001351213170042700170110ustar00rootroot00000000000000^dist/ ^django_model_utils\.egg-info/ ^HGREV$ ^\.coverage$ ^\.tox/ ^Django.*\.egg$ ^htmlcov/ django-model-utils-1.3.1/.hgtags000066400000000000000000000004321213170042700164640ustar00rootroot00000000000000b5efc435bb7e21b0d7ba422d28d174ccca3b3322 0.2.0 71b54b8b44fa2456beebd51c474ba55ad625486a 0.3.1 1e6f730f8c3a648c9fb70844a68fcfa663608600 0.4.0 004dbee634cb661c52acac034063989e521c4bb8 0.5.0 bd164041e5fabd64de19c38fefe9af9237a2a59e 1.0.0 92792fb14a51b580e5cc8991e815f3b3b57a6204 1.1.0 django-model-utils-1.3.1/.travis.yml000066400000000000000000000011421213170042700173160ustar00rootroot00000000000000language: python python: - "2.6" - "2.7" env: - DJANGO=Django==1.2.7 SOUTH=1 - DJANGO=Django==1.3.7 SOUTH=1 - DJANGO=Django==1.4.5 SOUTH=1 - DJANGO=Django==1.4.5 SOUTH=1 - DJANGO=Django==1.5 SOUTH=1 - DJANGO=https://github.com/django/django/tarball/master SOUTH=1 - DJANGO=Django==1.4.5 SOUTH=0 install: - pip install $DJANGO --use-mirrors - pip install coverage coveralls --use-mirrors - sh -c "if [ '$SOUTH' = '1' ]; then pip install South==0.7.6; fi" script: coverage run -a --branch --include="model_utils/*" --omit="model_utils/tests/*" setup.py test after_success: coveralls django-model-utils-1.3.1/AUTHORS.rst000066400000000000000000000010771213170042700170730ustar00rootroot00000000000000Alejandro Varas Carl Meyer Donald Stufft Facundo Gaich Felipe Prenholato Gregor Müllegger James Oakley Jannis Leidel Javier García Sogo Jeff Elmore ivirabyan Paul McLanahan Rinat Shigapov Ryan Kaskel Simon Meers sayane Trey Hunner zyegfryed django-model-utils-1.3.1/CHANGES.rst000066400000000000000000000074151213170042700170200ustar00rootroot00000000000000CHANGES ======= 1.3.1 (2013.04.11) ------------------ - Added explicit default to ``BooleanField`` in tests, for Django trunk compatibility. - Fix intermittent ``StatusField`` bug. Fixes GH-29. 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 García 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 Müllegger. 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-1.3.1/LICENSE.txt000066400000000000000000000030011213170042700170240ustar00rootroot00000000000000Copyright (c) 2009-2013, 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-1.3.1/MANIFEST.in000066400000000000000000000001641213170042700167460ustar00rootroot00000000000000include AUTHORS.rst include CHANGES.rst include LICENSE.txt include MANIFEST.in include README.rst include TODO.rst django-model-utils-1.3.1/README.rst000066400000000000000000000373431213170042700167100ustar00rootroot00000000000000================== django-model-utils ================== .. image:: https://secure.travis-ci.org/carljm/django-model-utils.png?branch=master :target: http://travis-ci.org/carljm/django-model-utils .. image:: https://coveralls.io/repos/carljm/django-model-utils/badge.png?branch=master :target: https://coveralls.io/r/carljm/django-model-utils Django model mixins and utilities. Installation ============ Install from PyPI with ``pip``:: pip install django-model-utils or get the `in-development version`_:: pip install django-model-utils==tip .. _in-development version: http://bitbucket.org/carljm/django-model-utils/get/tip.tar.gz#egg=django_model_utils-tip To use ``django-model-utils`` in your Django project, just import and use the utility classes described below; there is no need to modify your ``INSTALLED_APPS`` setting. Dependencies ------------ ``django-model-utils`` is tested with `Django`_ 1.2 and later on Python 2.6 and 2.7. .. _Django: http://www.djangoproject.com/ Contributing ============ Please file bugs and send pull requests to the `GitHub repository`_ and `issue tracker`_. .. _GitHub repository: https://github.com/carljm/django-model-utils/ .. _issue tracker: https://github.com/carljm/django-model-utils/issues (Until January 2013 django-model-utils primary development was hosted at `BitBucket`_; the issue tracker there will remain open until all issues and pull requests tracked in it are closed, but all new issues should be filed at GitHub.) .. _BitBucket: https://bitbucket.org/carljm/django-model-utils/overview Choices ======= ``Choices`` provides some conveniences for setting ``choices`` on a Django model field:: 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:: 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:: 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) StatusField =========== A simple convenience for giving a model a set of "states." ``StatusField`` is a ``CharField`` subclass that expects to find a ``STATUS`` class attribute on its model, 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:: 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 `Choices`_ instance, it can be an ordinary list of two-tuples). ``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 ============ A ``DateTimeField`` subclass that monitors another field on the model, and updates itself to the current date-time whenever the monitored field changes:: 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``.) 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:: 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:: >>> 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. TimeFramedModel =============== An abstract base class for any model that expresses a time-range. Adds ``start`` and ``end`` nullable DateTimeFields, and a ``timeframed`` manager that returns only objects for whom the current date-time lies within their time range. StatusModel =========== Pulls together `StatusField`_, `MonitorField`_ and `QueryManager`_ into an abstract base class for any model with a "status." Just provide a ``STATUS`` class-attribute (a `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:: 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() 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:: 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``:: 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:: nearby_places = Place.objects.select_subclasses("restaurant") # restaurants will be Restaurant instances, bars will still be Place instances ``InheritanceManager`` also provides a subclass-fetching alternative to the ``get()`` method:: 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. .. note:: Due to `Django bug #16572`_, on Django versions prior to 1.6 ``InheritanceManager`` only supports a single level of model inheritance; it won't work for grandchild models. .. note:: The implementation of ``InheritanceManager`` uses ``select_related`` internally. Due to `Django bug #16855`_, this currently means that it will override any previous ``select_related`` calls on the ``QuerySet``. .. _contributed by Jeff Elmore: http://jeffelmore.org/2010/11/11/automatic-downcasting-of-inherited-models-in-django/ .. _Django bug #16855: https://code.djangoproject.com/ticket/16855 .. _Django bug #16572: https://code.djangoproject.com/ticket/16572 TimeStampedModel ================ This abstract base class just provides self-updating ``created`` and ``modified`` fields on any model that inherits from it. 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:: 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). PassThroughManager ================== A common "gotcha" when defining methods on a custom manager class is that those same methods are not automatically also available on the QuerySets returned by that manager, so are not "chainable". This can be counterintuitive, as most of the public QuerySet API is mirrored on managers. It is possible to create a custom Manager that returns QuerySets that have the same additional methods, but this requires boilerplate code. The ``PassThroughManager`` class (`contributed by Paul McLanahan`_) removes this boilerplate. .. _contributed by Paul McLanahan: http://paulm.us/post/3717466639/passthroughmanager-for-django To use ``PassThroughManager``, rather than defining a custom manager with additional methods, define a custom ``QuerySet`` subclass with the additional methods you want, and pass that ``QuerySet`` subclass to the ``PassThroughManager.for_queryset_class()`` class method. The returned ``PassThroughManager`` subclass will always return instances of your custom ``QuerySet``, and you can also call methods of your custom ``QuerySet`` directly on the manager:: from datetime import datetime from django.db import models from django.db.models.query import QuerySet from model_utils.managers import PassThroughManager class PostQuerySet(QuerySet): def by_author(self, user): return self.filter(user=user) def published(self): return self.filter(published__lte=datetime.now()) def unpublished(self): return self.filter(published__gte=datetime.now()) class Post(models.Model): user = models.ForeignKey(User) published = models.DateTimeField() objects = PassThroughManager.for_queryset_class(PostQuerySet)() Post.objects.published() Post.objects.by_author(user=request.user).unpublished() ModelTracker ============ A ``ModelTracker`` can be added to a model to track changes in model fields. A ``ModelTracker`` allows querying for field changes since a model instance was last saved. An example of applying ``ModelTracker`` to a model:: from django.db import models from model_utils import ModelTracker class Post(models.Model): title = models.CharField(max_length=100) body = models.TextField() tracker = ModelTracker() Accessing a model 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:: >>> 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. has_changed ~~~~~~~~~~~ Returns ``True`` if the given field has changed since the last save:: >>> a = Post.objects.create(title='First Post') >>> a.title = 'Welcome' >>> a.tracker.has_changed('title') True >>> a.tracker.has_changed('body') False Returns ``True`` if the model instance hasn't been saved yet. 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:: >>> a = Post.objects.create(title='First Post') >>> a.title = 'Welcome' >>> a.body = 'First post!' >>> a.tracker.changed() {'title': 'First Post', 'body': ''} Returns ``{}`` if the model instance hasn't been saved yet. Tracking specific fields ------------------------ A fields parameter can be given to ``ModelTracker`` to limit model tracking to the specific fields:: from django.db import models from model_utils import ModelTracker class Post(models.Model): title = models.CharField(max_length=100) body = models.TextField() title_tracker = ModelTracker(fields=['title']) An example using the model specified above:: >>> a = Post.objects.create(title='First Post') >>> a.body = 'First post!' >>> a.title_tracker.changed() {} django-model-utils-1.3.1/TODO.rst000066400000000000000000000001171213170042700165050ustar00rootroot00000000000000TODO ==== * Switch to proper test skips once Django 1.3 is minimum supported. django-model-utils-1.3.1/model_utils/000077500000000000000000000000001213170042700175275ustar00rootroot00000000000000django-model-utils-1.3.1/model_utils/__init__.py000066400000000000000000000000771213170042700216440ustar00rootroot00000000000000from .choices import Choices from .tracker import ModelTracker django-model-utils-1.3.1/model_utils/choices.py000066400000000000000000000055151213170042700215240ustar00rootroot00000000000000class Choices(object): """ 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.) """ def __init__(self, *choices): self._full = [] self._choices = [] self._choice_dict = {} for choice in self.equalize(choices): self._full.append(choice) self._choices.append((choice[0], choice[2])) self._choice_dict[choice[1]] = choice[0] def equalize(self, choices): for choice in choices: if isinstance(choice, (list, tuple)): if len(choice) == 3: yield choice elif len(choice) == 2: yield (choice[0], choice[0], choice[1]) else: raise ValueError("Choices can't handle a list/tuple of length %s, only 2 or 3" % len(choice)) else: yield (choice, choice, choice) def __len__(self): return len(self._choices) def __iter__(self): return iter(self._choices) def __getattr__(self, attname): try: return self._choice_dict[attname] except KeyError: raise AttributeError(attname) def __getitem__(self, index): return self._choices[index] def __repr__(self): return '%s(%s)' % (self.__class__.__name__, ', '.join(("%s" % str(i) for i in self._full))) django-model-utils-1.3.1/model_utils/fields.py000066400000000000000000000201441213170042700213500ustar00rootroot00000000000000from datetime import datetime from django.db import models from django.conf import settings try: from django.utils.timezone import now as now except ImportError: now = datetime.now 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(AutoCreatedField, self).__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 pre_save(self, model_instance, add): value = now() 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) super(StatusField, self).__init__(*args, **kwargs) def prepare_class(self, sender, **kwargs): if not sender._meta.abstract and self.check_for_status: assert hasattr(sender, 'STATUS'), \ "To use StatusField, the model '%s' must have a STATUS choices class attribute." \ % sender.__name__ self._choices = sender.STATUS if not self.has_default(): self.default = tuple(sender.STATUS)[0][0] # set first as default def contribute_to_class(self, cls, name): models.signals.class_prepared.connect(self.prepare_class, sender=cls) super(StatusField, self).contribute_to_class(cls, name) 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 super(MonitorField, self).__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(MonitorField, self).contribute_to_class(cls, name) def get_monitored_value(self, instance): return getattr(instance, self.monitor) def _save_initial(self, sender, instance, **kwargs): 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: setattr(model_instance, self.attname, value) self._save_initial(model_instance.__class__, model_instance) return super(MonitorField, self).pre_save(model_instance, add) 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) _excerpt_field_name = lambda name: '_%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(object): 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 def _get_content(self): return self.instance.__dict__[self.field_name] def _set_content(self, val): setattr(self.instance, self.field_name, val) content = property(_get_content, _set_content) # 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) # allows display via templates without .content necessary def __unicode__(self): return self.content class SplitDescriptor(object): 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(SplitField, self).__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(SplitField, self).contribute_to_class(cls, name) setattr(cls, self.name, SplitDescriptor(self)) def pre_save(self, model_instance, add): value = super(SplitField, self).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._get_val_from_obj(obj) return value.content def get_prep_value(self, value): try: return value.content except AttributeError: return value # allow South to handle these fields smoothly try: from south.modelsinspector import add_introspection_rules # For a normal MarkupField, the add_excerpt_field attribute is # always True, which means no_excerpt_field arg will always be # True in a frozen MarkupField, which is what we want. add_introspection_rules(rules=[ ( (SplitField,), [], {'no_excerpt_field': ('add_excerpt_field', {})} ), ( (MonitorField,), [], {'monitor': ('monitor', {})} ), ( (StatusField,), [], {'no_check_for_status': ('check_for_status', {})} ), ], patterns=['model_utils\.fields\.']) except ImportError: pass django-model-utils-1.3.1/model_utils/managers.py000066400000000000000000000153061213170042700217030ustar00rootroot00000000000000import django from django.db import models from django.db.models.fields.related import OneToOneField from django.db.models.query import QuerySet from django.core.exceptions import ObjectDoesNotExist try: from django.db.models.constants import LOOKUP_SEP except ImportError: # Django < 1.5 from django.db.models.sql.constants import LOOKUP_SEP class InheritanceQuerySet(QuerySet): def select_subclasses(self, *subclasses): if not subclasses: # only recurse one level on Django < 1.6 to avoid triggering # https://code.djangoproject.com/ticket/16572 levels = None if django.VERSION < (1, 6, 0): levels = 1 subclasses = self._get_subclasses_recurse(self.model, levels=levels) # workaround https://code.djangoproject.com/ticket/16855 field_dict = self.query.select_related new_qs = self.select_related(*subclasses) if isinstance(new_qs.query.select_related, dict) and isinstance(field_dict, dict): new_qs.query.select_related.update(field_dict) new_qs.subclasses = subclasses return new_qs def _clone(self, klass=None, setup=False, **kwargs): for name in ['subclasses', '_annotated']: if hasattr(self, name): kwargs[name] = getattr(self, name) return super(InheritanceQuerySet, self)._clone(klass, setup, **kwargs) def annotate(self, *args, **kwargs): qset = super(InheritanceQuerySet, self).annotate(*args, **kwargs) qset._annotated = [a.default_alias for a in args] + kwargs.keys() return qset def iterator(self): iter = super(InheritanceQuerySet, self).iterator() if getattr(self, 'subclasses', False): for obj in iter: sub_obj = None for s in self.subclasses: sub_obj = self._get_sub_obj_recurse(obj, s) if sub_obj: break if not sub_obj: sub_obj = obj if getattr(self, '_annotated', False): for k in self._annotated: setattr(sub_obj, k, getattr(obj, k)) yield sub_obj else: for obj in iter: yield obj def _get_subclasses_recurse(self, model, levels=None): rels = [rel for rel in model._meta.get_all_related_objects() if isinstance(rel.field, OneToOneField) and issubclass(rel.field.model, model)] 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.var_name + LOOKUP_SEP + subclass) subclasses.append(rel.var_name) return subclasses 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 or node else: return node class InheritanceManager(models.Manager): use_for_related_fields = True def get_query_set(self): return InheritanceQuerySet(self.model) def select_subclasses(self, *subclasses): return self.get_query_set().select_subclasses(*subclasses) def get_subclass(self, *args, **kwargs): return self.get_query_set().select_subclasses().get(*args, **kwargs) class QueryManager(models.Manager): use_for_related_fields = True def __init__(self, *args, **kwargs): if args: self._q = args[0] else: self._q = models.Q(**kwargs) self._order_by = None super(QueryManager, self).__init__() def order_by(self, *args): self._order_by = args return self def get_query_set(self): qs = super(QueryManager, self).get_query_set().filter(self._q) if self._order_by is not None: return qs.order_by(*self._order_by) return qs class PassThroughManager(models.Manager): """ Inherit from this Manager to enable you to call any methods from your custom QuerySet class from your manager. Simply define your QuerySet class, and return an instance of it from your manager's `get_query_set` method. Alternately, if you don't need any extra methods on your manager that aren't on your QuerySet, then just pass your QuerySet class to the ``for_queryset_class`` class method. class PostQuerySet(QuerySet): def enabled(self): return self.filter(disabled=False) class Post(models.Model): objects = PassThroughManager.for_queryset_class(PostQuerySet)() """ # pickling causes recursion errors _deny_methods = ['__getstate__', '__setstate__', '__getinitargs__', '__getnewargs__', '__copy__', '__deepcopy__', '_db'] def __init__(self, queryset_cls=None): self._queryset_cls = queryset_cls super(PassThroughManager, self).__init__() def __getattr__(self, name): if name in self._deny_methods: raise AttributeError(name) return getattr(self.get_query_set(), name) def get_query_set(self): if self._queryset_cls is not None: kwargs = {'model': self.model} kwargs['using'] = self._db return self._queryset_cls(**kwargs) return super(PassThroughManager, self).get_query_set() @classmethod def for_queryset_class(cls, queryset_cls): return create_pass_through_manager_for_queryset_class(cls, queryset_cls) def create_pass_through_manager_for_queryset_class(base, queryset_cls): class _PassThroughManager(base): def __init__(self): return super(_PassThroughManager, self).__init__() def get_query_set(self): kwargs = {} kwargs["using"] = self._db return queryset_cls(self.model, **kwargs) def __reduce__(self): # our pickling support breaks for subclasses (e.g. RelatedManager) if self.__class__ is not _PassThroughManager: return super(_PassThroughManager, self).__reduce__() return ( unpickle_pass_through_manager_for_queryset_class, (base, queryset_cls), self.__dict__, ) return _PassThroughManager def unpickle_pass_through_manager_for_queryset_class(base, queryset_cls): cls = create_pass_through_manager_for_queryset_class(base, queryset_cls) return cls.__new__(cls) django-model-utils-1.3.1/model_utils/models.py000066400000000000000000000061531213170042700213710ustar00rootroot00000000000000from datetime import datetime from django.db import models from django.utils.translation import ugettext_lazy as _ from django.db.models.fields import FieldDoesNotExist from django.core.exceptions import ImproperlyConfigured from model_utils.managers import QueryManager from model_utils.fields import AutoCreatedField, AutoLastModifiedField, \ StatusField, MonitorField try: from django.utils.timezone import now as now except ImportError: now = datetime.now class TimeStampedModel(models.Model): """ An abstract base class model that provides self-updating ``created`` and ``modified`` fields. """ created = AutoCreatedField(_('created')) modified = AutoLastModifiedField(_('modified')) 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') 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 for value, name in getattr(sender, 'STATUS', ()): try: sender._meta.get_field(name) raise ImproperlyConfigured("StatusModel: Model '%s' has a field " "named '%s' which conflicts with a " "status of the same name." % (sender.__name__, name)) except FieldDoesNotExist: pass sender.add_to_class(value, QueryManager(status=value)) def add_timeframed_query_manager(sender, **kwargs): """ Add a QueryManager for a specific timeframe. """ if not issubclass(sender, TimeFramedModel): return try: sender._meta.get_field('timeframed') raise ImproperlyConfigured("Model '%s' has a field named " "'timeframed' which conflicts with " "the TimeFramedModel manager." % sender.__name__) except FieldDoesNotExist: pass 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) django-model-utils-1.3.1/model_utils/tests/000077500000000000000000000000001213170042700206715ustar00rootroot00000000000000django-model-utils-1.3.1/model_utils/tests/__init__.py000066400000000000000000000000001213170042700227700ustar00rootroot00000000000000django-model-utils-1.3.1/model_utils/tests/models.py000066400000000000000000000133731213170042700225350ustar00rootroot00000000000000from django.db import models from django.utils.translation import ugettext_lazy as _ from model_utils.models import TimeStampedModel, StatusModel, TimeFramedModel from model_utils.tracker import ModelTracker from model_utils.managers import QueryManager, InheritanceManager, PassThroughManager from model_utils.fields import SplitField, MonitorField, StatusField from model_utils import Choices 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) normal_field = models.TextField() objects = InheritanceManager() class InheritanceManagerTestChild1(InheritanceManagerTestParent): non_related_field_using_descriptor_2 = models.FileField(upload_to="test") normal_field_2 = models.TextField() pass class InheritanceManagerTestGrandChild1(InheritanceManagerTestChild1): text_field = models.TextField() class InheritanceManagerTestChild2(InheritanceManagerTestParent): non_related_field_using_descriptor_2 = models.FileField(upload_to="test") normal_field_2 = models.TextField() pass class TimeStamp(TimeStampedModel): pass class TimeFrame(TimeFramedModel): pass class TimeFrameManagerAdded(TimeFramedModel): pass class Monitored(models.Model): name = models.CharField(max_length=25) name_changed = MonitorField(monitor="name") 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 Post(models.Model): published = models.BooleanField() confirmed = models.BooleanField() 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(object): def by_author(self, name): return self.filter(author=name) class PublishedMixin(object): 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_query_set(self): kwargs = {} if hasattr(self, "_db"): kwargs["using"] = self._db return ByAuthorQuerySet(self.model, **kwargs).filter(feature=True) class DudeQuerySet(models.query.QuerySet): def abiding(self): return self.filter(abides=True) def rug_positive(self): return self.filter(has_rug=True) def rug_negative(self): return self.filter(has_rug=False) def by_name(self, name): return self.filter(name__iexact=name) class AbidingManager(PassThroughManager): def get_query_set(self): return DudeQuerySet(self.model).abiding() def get_stats(self): return { "abiding_count": self.count(), "rug_count": self.rug_positive().count(), } class Dude(models.Model): abides = models.BooleanField(default=True) name = models.CharField(max_length=20) has_rug = models.BooleanField(default=False) objects = PassThroughManager(DudeQuerySet) abiders = AbidingManager() class Car(models.Model): name = models.CharField(max_length=20) owner = models.ForeignKey(Dude, related_name='cars_owned') objects = PassThroughManager(DudeQuerySet) class SpotQuerySet(models.query.QuerySet): def closed(self): return self.filter(closed=True) def secured(self): return self.filter(secure=True) class Spot(models.Model): name = models.CharField(max_length=20) secure = models.BooleanField(default=True) closed = models.BooleanField(default=False) owner = models.ForeignKey(Dude, related_name='spots_owned') objects = PassThroughManager.for_queryset_class(SpotQuerySet)() class Tracked(models.Model): name = models.CharField(max_length=20) number = models.IntegerField() tracker = ModelTracker() class TrackedNotDefault(models.Model): name = models.CharField(max_length=20) number = models.IntegerField() name_tracker = ModelTracker(fields=['name']) class TrackedMultiple(models.Model): name = models.CharField(max_length=20) number = models.IntegerField() name_tracker = ModelTracker(fields=['name']) number_tracker = ModelTracker(fields=['number']) 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() django-model-utils-1.3.1/model_utils/tests/tests.py000066400000000000000000000731661213170042700224220ustar00rootroot00000000000000from __future__ import with_statement import pickle from datetime import datetime, timedelta import django from django.db import models from django.db.models.fields import FieldDoesNotExist from django.core.exceptions import ImproperlyConfigured, FieldError from django.test import TestCase from model_utils import Choices, ModelTracker from model_utils.fields import get_excerpt, MonitorField, StatusField from model_utils.managers import QueryManager from model_utils.models import StatusModel, TimeFramedModel from model_utils.tests.models import ( InheritanceManagerTestRelated, InheritanceManagerTestGrandChild1, InheritanceManagerTestParent, InheritanceManagerTestChild1, InheritanceManagerTestChild2, TimeStamp, Post, Article, Status, StatusPlainTuple, TimeFrame, Monitored, StatusManagerAdded, TimeFrameManagerAdded, Dude, SplitFieldAbstractParent, Car, Spot, Tracked, TrackedNotDefault, TrackedMultiple, StatusFieldDefaultFilled, StatusFieldDefaultNotFilled) class GetExcerptTests(TestCase): def test_split(self): e = get_excerpt("some content\n\n\n\nsome more") self.assertEquals(e, 'some content\n') def test_auto_split(self): e = get_excerpt("para one\n\npara two\n\npara three") self.assertEquals(e, 'para one\n\npara two') def test_middle_of_para(self): e = get_excerpt("some text\n\nmore text") self.assertEquals(e, 'some text') def test_middle_of_line(self): e = get_excerpt("some text more text") self.assertEquals(e, "some text more text") class SplitFieldTests(TestCase): full_text = u'summary\n\n\n\nmore' excerpt = u'summary\n' def setUp(self): self.post = Article.objects.create( title='example post', body=self.full_text) def test_unicode_content(self): self.assertEquals(unicode(self.post.body), self.full_text) def test_excerpt(self): self.assertEquals(self.post.body.excerpt, self.excerpt) def test_content(self): self.assertEquals(self.post.body.content, self.full_text) def test_has_more(self): self.failUnless(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.failIf(post.body.has_more) def test_load_back(self): post = Article.objects.get(pk=self.post.pk) self.assertEquals(post.body.content, self.post.body.content) self.assertEquals(post.body.excerpt, self.post.body.excerpt) def test_assign_to_body(self): new_text = u'different\n\n\n\nother' self.post.body = new_text self.post.save() self.assertEquals(unicode(self.post.body), new_text) def test_assign_to_content(self): new_text = u'different\n\n\n\nother' self.post.body.content = new_text self.post.save() self.assertEquals(unicode(self.post.body), new_text) def test_assign_to_excerpt(self): def _invalid_assignment(): self.post.body.excerpt = 'this should fail' self.assertRaises(AttributeError, _invalid_assignment) def test_access_via_class(self): def _invalid_access(): Article.body self.assertRaises(AttributeError, _invalid_access) def test_none(self): a = Article(title='Some Title', body=None) self.assertEquals(a.body, None) def test_assign_splittext(self): a = Article(title='Some Title') a.body = self.post.body self.assertEquals(a.body.excerpt, u'summary\n') def test_value_to_string(self): f = self.post._meta.get_field('body') self.assertEquals(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"]) class MonitorFieldTests(TestCase): def setUp(self): self.instance = Monitored(name='Charlie') self.created = self.instance.name_changed def test_save_no_change(self): self.instance.save() self.assertEquals(self.instance.name_changed, self.created) def test_save_changed(self): self.instance.name = 'Maria' self.instance.save() self.failUnless(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.assertEquals(self.instance.name_changed, changed) def test_no_monitor_arg(self): self.assertRaises(TypeError, MonitorField) class StatusFieldTests(TestCase): def test_status_with_default_filled(self): instance = StatusFieldDefaultFilled() self.assertEquals(instance.status, instance.STATUS.yes) def test_status_with_default_not_filled(self): instance = StatusFieldDefaultNotFilled() self.assertEquals(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) class ChoicesTests(TestCase): def setUp(self): self.STATUS = Choices('DRAFT', 'PUBLISHED') def test_getattr(self): self.assertEquals(self.STATUS.DRAFT, 'DRAFT') def test_indexing(self): self.assertEquals(self.STATUS[1], ('PUBLISHED', 'PUBLISHED')) def test_iteration(self): self.assertEquals(tuple(self.STATUS), (('DRAFT', 'DRAFT'), ('PUBLISHED', 'PUBLISHED'))) def test_len(self): self.assertEqual(len(self.STATUS), 2) def test_repr(self): self.assertEquals(repr(self.STATUS), "Choices(" "('DRAFT', 'DRAFT', 'DRAFT'), " "('PUBLISHED', 'PUBLISHED', 'PUBLISHED'))") def test_wrong_length_tuple(self): self.assertRaises(ValueError, Choices, ('a',)) class LabelChoicesTests(ChoicesTests): def setUp(self): self.STATUS = Choices( ('DRAFT', 'is draft'), ('PUBLISHED', 'is published'), 'DELETED', ) def test_iteration(self): self.assertEquals(tuple(self.STATUS), ( ('DRAFT', 'is draft'), ('PUBLISHED', 'is published'), ('DELETED', 'DELETED')) ) def test_indexing(self): self.assertEquals(self.STATUS[1], ('PUBLISHED', 'is published')) def test_default(self): self.assertEquals(self.STATUS.DELETED, 'DELETED') def test_provided(self): self.assertEquals(self.STATUS.DRAFT, 'DRAFT') def test_len(self): self.assertEqual(len(self.STATUS), 3) def test_repr(self): self.assertEquals(repr(self.STATUS), "Choices(" "('DRAFT', 'DRAFT', 'is draft'), " "('PUBLISHED', 'PUBLISHED', 'is published'), " "('DELETED', 'DELETED', 'DELETED'))") 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_indexing(self): self.assertEquals(self.STATUS[1], (1, 'is published')) def test_getattr(self): self.assertEquals(self.STATUS.DRAFT, 0) def test_len(self): self.assertEqual(len(self.STATUS), 3) def test_repr(self): self.assertEquals(repr(self.STATUS), "Choices(" "(0, 'DRAFT', 'is draft'), " "(1, 'PUBLISHED', 'is published'), " "(2, 'DELETED', 'is deleted'))") class InheritanceManagerTests(TestCase): def setUp(self): self.child1 = InheritanceManagerTestChild1.objects.create() self.child2 = InheritanceManagerTestChild2.objects.create() self.grandchild1 = InheritanceManagerTestGrandChild1.objects.create() def get_manager(self): return InheritanceManagerTestParent.objects def test_normal(self): children = set([ InheritanceManagerTestParent(pk=self.child1.pk), InheritanceManagerTestParent(pk=self.child2.pk), InheritanceManagerTestParent(pk=self.grandchild1.pk), ]) self.assertEquals(set(self.get_manager().all()), children) def test_select_all_subclasses(self): children = set([self.child1, self.child2]) if django.VERSION >= (1, 6, 0): children.add(self.grandchild1) else: children.add(InheritanceManagerTestChild1(pk=self.grandchild1.pk)) self.assertEquals( set(self.get_manager().select_subclasses()), children) def test_select_specific_subclasses(self): children = set([ self.child1, InheritanceManagerTestParent(pk=self.child2.pk), InheritanceManagerTestChild1(pk=self.grandchild1.pk), ]) self.assertEquals( set( self.get_manager().select_subclasses( "inheritancemanagertestchild1") ), children, ) def test_select_specific_grandchildren(self): if django.VERSION >= (1, 6, 0): children = set([ self.child1, InheritanceManagerTestParent(pk=self.child2.pk), self.grandchild1, ]) self.assertEquals( set( self.get_manager().select_subclasses( "inheritancemanagertestchild1__" "inheritancemanagertestgrandchild1" ) ), children, ) def test_get_subclass(self): self.assertEquals( self.get_manager().get_subclass(pk=self.child1.pk), self.child1) def test_prior_select_related(self): # Django 1.2 doesn't have assertNumQueries if django.VERSION >= (1, 3): with self.assertNumQueries(1): obj = self.get_manager().select_related( "inheritancemanagertestchild1").select_subclasses( "inheritancemanagertestchild2").get(pk=self.child1.pk) obj.inheritancemanagertestchild1 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) 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_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) class TimeStampedModelTests(TestCase): def test_created(self): t1 = TimeStamp.objects.create() t2 = TimeStamp.objects.create() self.assert_(t2.created > t1.created) def test_modified(self): t1 = TimeStamp.objects.create() t2 = TimeStamp.objects.create() t1.save() self.assert_(t2.modified < t1.modified) 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.assertEquals(TimeFrame.timeframed.count(), 0) def test_finished(self): TimeFrame.objects.create(end=self.now-timedelta(days=1)) self.assertEquals(TimeFrame.timeframed.count(), 0) def test_no_end(self): TimeFrame.objects.create(start=self.now-timedelta(days=10)) self.assertEquals(TimeFrame.timeframed.count(), 1) def test_no_start(self): TimeFrame.objects.create(end=self.now+timedelta(days=2)) self.assertEquals(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.assertEquals(TimeFrame.timeframed.count(), 1) class TimeFrameManagerAddedTests(TestCase): def test_manager_available(self): self.assert_(isinstance(TimeFrameManagerAdded.timeframed, QueryManager)) def test_conflict_error(self): def _run(): class ErrorModel(TimeFramedModel): timeframed = models.BooleanField() self.assertRaises(ImproperlyConfigured, _run) 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): c1 = self.model.objects.create() c2 = self.model.objects.create() self.assert_(c2.status_changed > c1.status_changed) self.assertEquals(self.model.active.count(), 2) self.assertEquals(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.assertEquals(self.model.active.count(), 0) self.assertEquals(self.model.on_hold.count(), 1) self.assert_(t1.status_changed > date_created) date_changed = t1.status_changed t1.save() self.assertEquals(t1.status_changed, date_changed) date_active_again = t1.status_changed t1.status = self.active t1.save() self.assert_(t1.status_changed > date_active_again) class StatusModelPlainTupleTests(StatusModelTests): def setUp(self): self.model = StatusPlainTuple self.on_hold = StatusPlainTuple.STATUS[2][0] self.active = StatusPlainTuple.STATUS[0][0] class StatusManagerAddedTests(TestCase): def test_manager_available(self): self.assert_(isinstance(StatusManagerAdded.active, QueryManager)) def test_conflict_error(self): def _run(): class ErrorModel(StatusModel): STATUS = ( ('active', 'active'), ('deleted', 'deleted'), ) active = models.BooleanField() self.assertRaises(ImproperlyConfigured, _run) 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.assertEquals([p.order for p in qs], [0, 1, 4, 5]) def test_passing_Q(self): qs = Post.public_confirmed.all() self.assertEquals([p.order for p in qs], [0, 1]) def test_ordering(self): qs = Post.public_reversed.all() self.assertEquals([p.order for p in qs], [5, 4, 1, 0]) try: from south.modelsinspector import introspector except ImportError: introspector = None # @@@ use skipUnless once Django 1.3 is minimum supported version if introspector: class SouthFreezingTests(TestCase): def test_introspector_adds_no_excerpt_field(self): mf = Article._meta.get_field('body') args, kwargs = introspector(mf) self.assertEquals(kwargs['no_excerpt_field'], 'True') def test_no_excerpt_field_works(self): from models import NoRendered self.assertRaises(FieldDoesNotExist, NoRendered._meta.get_field, '_body_excerpt') def test_status_field_no_check_for_status(self): sf = StatusFieldDefaultFilled._meta.get_field('status') args, kwargs = introspector(sf) self.assertEqual(kwargs['no_check_for_status'], 'True') class PassThroughManagerTests(TestCase): def setUp(self): Dude.objects.create(name='The Dude', abides=True, has_rug=False) Dude.objects.create(name='His Dudeness', abides=False, has_rug=True) Dude.objects.create(name='Duder', abides=False, has_rug=False) Dude.objects.create(name='El Duderino', abides=True, has_rug=True) def test_chaining(self): self.assertEqual(Dude.objects.by_name('Duder').count(), 1) self.assertEqual(Dude.objects.all().by_name('Duder').count(), 1) self.assertEqual(Dude.abiders.rug_positive().count(), 1) self.assertEqual(Dude.abiders.all().rug_positive().count(), 1) def test_manager_only_methods(self): stats = Dude.abiders.get_stats() self.assertEqual(stats['rug_count'], 1) def notonqs(): Dude.abiders.all().get_stats() self.assertRaises(AttributeError, notonqs) def test_queryset_pickling(self): qs = Dude.objects.all() saltyqs = pickle.dumps(qs) unqs = pickle.loads(saltyqs) self.assertEqual(unqs.by_name('The Dude').count(), 1) def test_queryset_not_available_on_related_manager(self): dude = Dude.objects.by_name('Duder').get() Car.objects.create(name='Ford', owner=dude) self.assertFalse(hasattr(dude.cars_owned, 'by_name')) class CreatePassThroughManagerTests(TestCase): def setUp(self): self.dude = Dude.objects.create(name='El Duderino') def test_reverse_manager(self): Spot.objects.create( name='The Crib', owner=self.dude, closed=True, secure=True) self.assertEqual(self.dude.spots_owned.closed().count(), 1) def test_related_queryset_pickling(self): Spot.objects.create( name='The Crib', owner=self.dude, closed=True, secure=True) qs = self.dude.spots_owned.closed() pickled_qs = pickle.dumps(qs) unpickled_qs = pickle.loads(pickled_qs) self.assertEqual(unpickled_qs.secured().count(), 1) def test_related_manager_create(self): self.dude.spots_owned.create(name='The Crib', closed=True, secure=True) class ModelTrackerTestCase(TestCase): tracker = None def assertHasChanged(self, **kwargs): tracker = kwargs.pop('tracker', self.tracker) for field, value in kwargs.iteritems(): if value is None: 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.iteritems(): 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.iteritems(): setattr(self.instance, field, value) self.instance.save() class ModelTrackerCommonTests(object): def test_pre_save_has_changed(self): self.assertHasChanged(name=True, number=True) self.instance.name = 'new age' 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() 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 ModelTrackerTests(ModelTrackerTestCase, ModelTrackerCommonTests): def setUp(self): self.instance = Tracked() self.tracker = self.instance.tracker def test_descriptor(self): self.assertTrue(isinstance(Tracked.tracker, ModelTracker)) def test_first_save(self): self.assertHasChanged(name=True, number=True) self.assertPrevious(name=None, number=None) self.assertCurrent(name='', number=None, id=None) 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', number=4, id=None) self.assertChanged() # Django 1.4 doesn't have update_fields if django.VERSION >= (1, 5, 0): self.instance.save(update_fields=[]) self.assertHasChanged(name=True, number=True) self.assertPrevious(name=None, number=None) self.assertCurrent(name='retro', number=4, id=None) self.assertChanged() self.assertRaises(ValueError, self.instance.save, update_fields=['number']) def test_post_save_has_changed(self): self.update_instance(name='retro', number=4) self.assertHasChanged(name=False, number=False) self.instance.name = 'new age' self.assertHasChanged(name=True, number=False) self.instance.number = 8 self.assertHasChanged(name=True, number=True) self.instance.name = 'retro' self.assertHasChanged(name=False, number=True) def test_post_save_previous(self): self.update_instance(name='retro', number=4) self.instance.name = 'new age' self.assertPrevious(name='retro', number=4) 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', number=4) self.instance.name = 'retro' self.assertChanged(number=4) def test_current(self): self.assertCurrent(id=None, name='', number=None) self.instance.name = 'new age' self.assertCurrent(id=None, name='new age', number=None) self.instance.number = 8 self.assertCurrent(id=None, name='new age', number=8) self.instance.save() self.assertCurrent(id=self.instance.id, name='new age', number=8) def test_update_fields(self): # Django 1.4 doesn't have update_fields if django.VERSION >= (1, 5, 0): self.update_instance(name='retro', number=4) self.assertChanged() self.instance.name = 'new age' self.instance.number = 8 self.assertChanged(name='retro', number=4) self.instance.save(update_fields=[]) self.assertChanged(name='retro', number=4) self.instance.save(update_fields=['name']) in_db = Tracked.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) self.instance.save(update_fields=['number']) self.assertChanged() in_db = Tracked.objects.get(id=self.instance.id) self.assertEqual(in_db.name, self.instance.name) self.assertEqual(in_db.number, self.instance.number) class FieldTrackedModelCustomTests(ModelTrackerTestCase, ModelTrackerCommonTests): def setUp(self): self.instance = TrackedNotDefault() self.tracker = self.instance.name_tracker 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') class FieldTrackedModelMultiTests(ModelTrackerTestCase, ModelTrackerCommonTests): def setUp(self): self.instance = TrackedMultiple() self.trackers = [self.instance.name_tracker, self.instance.number_tracker] def test_pre_save_has_changed(self): for tracker in self.trackers: self.tracker = tracker super(FieldTrackedModelMultiTests, self).test_pre_save_has_changed() def test_pre_save_changed(self): for tracker in self.trackers: self.tracker = tracker super(FieldTrackedModelMultiTests, self).test_pre_save_changed() def test_pre_save_previous(self): for tracker in self.trackers: self.tracker = tracker super(FieldTrackedModelMultiTests, self).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) django-model-utils-1.3.1/model_utils/tracker.py000066400000000000000000000052461213170042700215430ustar00rootroot00000000000000from django.db import models from django.core.exceptions import FieldError class ModelTracker(object): def __init__(self, fields=None): self.fields = fields 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.local_fields] models.signals.post_init.connect(self.initialize_tracker, sender=sender) setattr(sender, self.name, self) def initialize_tracker(self, sender, instance, **kwargs): tracker = ModelInstanceTracker(instance, self.fields) setattr(instance, self.attname, tracker) tracker.set_saved_fields() self.patch_save(instance) def patch_save(self, instance): original_save = instance.save def save(**kwargs): ret = original_save(**kwargs) getattr(instance, self.attname).set_saved_fields( fields=kwargs.get('update_fields')) return ret instance.save = save def __get__(self, instance, owner): if instance is None: return self else: return getattr(instance, self.attname) class ModelInstanceTracker(object): def __init__(self, instance, fields): self.instance = instance self.fields = fields 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)) def current(self, fields=None): if fields is None: fields = self.fields return dict((f, getattr(self.instance, f)) for f in fields) 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.saved_data.get(field) != getattr(self.instance, field) else: raise FieldError('field "%s" not tracked' % field) def previous(self, field): """Return currently saved value of given field""" return self.saved_data.get(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.iteritems() current = self.current() return dict((k, v) for k, v in saved if v != current[k]) django-model-utils-1.3.1/runtests.py000077500000000000000000000015361213170042700174600ustar00rootroot00000000000000#!/usr/bin/env python import os, sys from django.conf import settings if not settings.configured: settings_dict = dict( INSTALLED_APPS=( 'django.contrib.contenttypes', 'model_utils', 'model_utils.tests', ), DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3" } }, ) settings.configure(**settings_dict) def runtests(*test_args): if not test_args: test_args = ['tests'] parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) from django.test.simple import DjangoTestSuiteRunner failures = DjangoTestSuiteRunner( verbosity=1, interactive=True, failfast=False).run_tests(test_args) sys.exit(failures) if __name__ == '__main__': runtests() django-model-utils-1.3.1/runtests.sh000077500000000000000000000001371213170042700174360ustar00rootroot00000000000000#!/bin/sh coverage erase tox coverage html --include=model_utils/* --omit=model_utils/tests/* django-model-utils-1.3.1/setup.py000066400000000000000000000016241213170042700167240ustar00rootroot00000000000000from setuptools import setup, find_packages long_description = (open('README.rst').read() + open('CHANGES.rst').read() + open('TODO.rst').read()) setup( name='django-model-utils', version='1.3.1', description='Django model mixins and utilities', long_description=long_description, author='Carl Meyer', author_email='carl@oddbird.net', url='https://github.com/carljm/django-model-utils/', packages=find_packages(), classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], zip_safe=False, tests_require=["Django>=1.2"], test_suite='runtests.runtests' ) django-model-utils-1.3.1/tox.ini000066400000000000000000000021301213170042700165160ustar00rootroot00000000000000[tox] envlist=py26-1.2,py26-1.3,py26-1.4,py26,py26-trunk,py27-1.2,py27-1.3,py27-1.4,py27,py27-trunk,py27-nosouth [testenv] deps= django==1.5.0 South==0.7.6 coverage==3.6 commands=coverage run -a --branch setup.py test [testenv:py26-1.2] basepython=python2.6 deps= django==1.2.7 South==0.7.6 coverage==3.6 [testenv:py26-1.3] basepython=python2.6 deps= django==1.3.7 South==0.7.6 coverage==3.6 [testenv:py26-1.4] basepython=python2.6 deps= django==1.4.5 South==0.7.6 coverage==3.6 [testenv:py26-trunk] basepython=python2.6 deps= https://github.com/django/django/tarball/master South==0.7.6 coverage==3.6 [testenv:py27-1.2] basepython=python2.7 deps= django==1.2.7 South==0.7.6 coverage==3.6 [testenv:py27-1.3] basepython=python2.7 deps= django==1.3.7 South==0.7.6 coverage==3.6 [testenv:py27-1.4] basepython=python2.7 deps= django==1.4.5 South==0.7.6 coverage==3.6 [testenv:py27-trunk] basepython=python2.7 deps= https://github.com/django/django/tarball/master South==0.7.6 coverage==3.6 [testenv:py27-nosouth] deps= django==1.4.3 coverage==3.6