|
Project Information
|
Defines PolymorphicModel, which includes a downcast() method to return the model instance as its most derived type. Based on dan90's snippet. polytest/models.pyfrom django.db import models from polymorphic.models import * from django.db import connection def queries(): print len(connection.queries) connection.queries = [] class Base(models.Model): __metaclass__ = PolymorphicMetaclass class Derived(Base): pass class DowncastBase(models.Model): __metaclass__ = DowncastMetaclass class DowncastDerived(DowncastBase): pass $ ./manage.py shell>>> from polytest.models import * Example1: PolymorphicMetaclassqueries return base class objects, which can be downcast() >>> Derived().save() >>> queries() 4 >>> Base.objects.all() [<Base: Base object>] >>> queries() 1 >>> Base.objects.all()[0].downcast() <Derived: Derived object> >>> queries() 3 Example2: DowncastMetaclassqueries automatically downcast all objects >>> DowncastDerived().save() >>> queries() 4 >>> DowncastBase.objects.all() [<DowncastDerived: DowncastDerived object>] >>> queries() 3 Example3: Comparing queries with 10 objects in result>>> [Derived().save() for i in range(9)] [None, None, None, None, None, None, None, None, None] >>> queries() 27 >>> Base.objects.all() [<Base: Base object>, <Base: Base object>, <Base: Base object>, <Base: Base object>, <Base: Base object>, <Base: Base object>, <Base: Base object>, <Base: Base object>, <Base: Base object>, <Base: Base object>] >>> queries() 1 >>> [DowncastDerived().save() for i in range(9)] [None, None, None, None, None, None, None, None, None] >>> queries() 27 >>> DowncastBase.objects.all() DowncastBase.objects.all() [<DowncastDerived: DowncastDerived object>, <DowncastDerived: DowncastDerived object>, <DowncastDerived: DowncastDerived object>, <DowncastDerived: DowncastDerived object>, <DowncastDerived: DowncastDerived object>, <DowncastDerived: DowncastDerived object>, <DowncastDerived: DowncastDerived object>, <DowncastDerived: DowncastDerived object>, <DowncastDerived: DowncastDerived object>, <DowncastDerived: DowncastDerived object>] >>> queries() 21 |