As in this question , except that I want to have queries returning a mixed body of objects:
>>> Product.objects.all() [<SimpleProduct: ...>, <OtherProduct: ...>, <BlueProduct: ...>, ...]
I realized that I can’t just set Product.Meta.abstract to true or otherwise just OR along with requests for different objects. Ok, but these are all subclasses of the general class, so if I leave my superclass as non-abstract, I should be happy as long as I can get his manager to return objects of the corresponding class. The request code in django does its thing and simply calls Product () calls. It sounds simple enough, except that it explodes when I redefine Product.__new__ , I guess because of __metaclass__ in Model ... Here is a non-jango code that behaves very well as I want it:
class Top(object): _counter = 0 def __init__(self, arg): Top._counter += 1 print "Top#__init__(%s) called %d times" % (arg, Top._counter) class A(Top): def __new__(cls, *args, **kwargs): if cls is A and len(args) > 0: if args[0] is B.fav: return B(*args, **kwargs) elif args[0] is C.fav: return C(*args, **kwargs) else: print "PRETENDING TO BE ABSTRACT" return None
But this fails if I inherit from django.db.models.Model instead of object :
File "/home/martin/beehive/apps/hello_world/models.py", line 50, in <module> A(0) TypeError: unbound method __new__() must be called with A instance as first argument (got ModelBase instance instead)
Which one is a crappy return line; I also cannot enter the frame of my __new__ code in the debugger. I tried super(A, cls) , Top , super(A, A) in different ways, and all of the above, combined with passing cls as the first argument __new__ all to no avail. Why does it hit me so hard? Do I have to define django metaclasses to be able to fix this, or is there a better way to achieve my goals?
python metaclass django django-models django-queryset
outofculture
source share