I’ve been trying to figure this out for a while now with little success. I’m attempting to write a class factory that plays nice with Django’s ORM, so that I can take a model schema like this:
Product
SubclassOfProduct0
SubclassOfProduct1
....
To work like this:
Product.objects.get(pk=7) // returns the result of SubclassOfProduct0(pk=7)
Product.objects.filter(propname="w00t") // returns a QuerySet of Product objects
So I was thinking something like this:
class ProductManager(models.Manager):
def get(self, *a, **kwa):
# Get the id from Products (somehow)
if product.type == Product.TYPE_SUBCLASS0:
return ProductSubClass0.objects.get(pk=kwa["pk"])
class Product(models.Model):
TYPE_SUBCLASS0 = 0
TYPE_SUBCLASS1 = 1
objects = ProductManager()
def __init__(self, *a, **kwa):
self.set_defaults()
def set_defaults(self):
pass
class ProductSubClass0(models.Model):
def set_defaults(self):
self.type == self.TYPE_SUBCLASS0
…but I don’t know how to do it “right”. Can someone shed some light here?
Django Tagging has a great example in the models.py as to how it figures out the content type of specific classes. I’m currently using the pattern in another module I developed with permissions.