I am still a bit confused about the relation of Proxy models to their Superclasses in django. My question now is how do I get a instance of a Proxy model from an already retrieved instance of the Superclass?
So, lets say I have:
class Animal(models.Model):
type = models.CharField(max_length=20)
name = models.CharField(max_length=40)
class Dog(Animal):
class Meta:
proxy = True
def make_noise(self):
print "Woof Woof"
Class Cat(Animal):
class Meta:
proxy = True
def make_noise(self):
print "Meow Meow"
animals = Animal.objects.all()
for animal in animals:
if (animal.type == "cat"):
animal_proxy = # make me a cat
elif (animal.type == "dog"):
animal_proxy = # make me a dog
animal_proxy.make_noise()
OK. So.. What goes into “# make me a cat” that doesn’t require a query back to the database such as:
animal_proxy = Cat.objects.get(id=animal.id)
Is there a simple way to create an instance of Cat from an instance of Animal that I know is a cat?
You are trying to implement persistence for an inheritance hierarchy. Using one concrete table and a
typeswitch is a nice way to do this. However I think that your implementation, specifically:is going against the grain of Django. The switching on type shouldn’t be extraneous to the proxy (or model) class.
If I were you, I’d do the following:
First, add a “type aware” manager to the proxy models. This will ensure that
Dog.objectswill always fetchAnimalinstances withtype="dog"andCat.objectswill fetchAnimalinstances withtype="cat".Second, fetch subclass instances separately. You can then combine them before operating on them. I’ve used
itertools.chainto combine twoQuerysets.