django class with an array of "parent" foreignkeys issue

Posted by user298032 on Stack Overflow See other posts from Stack Overflow or by user298032
Published on 2010-03-20T15:04:01Z Indexed on 2010/03/20 15:11 UTC
Read the original article Hit count: 305

Filed under:
|
|

Let's say I have a class called Fruit with child classes of the different kinds of Fruit with their own specific attributes, and I want to collect them in a FruitBasket:

class Fruit(models.Model):
    type = models.CharField(max_length=120,default='banana',choices=FRUIT_TYPES)
    ...

class Banana(Fruit):
    """banana (fruit type)"""
    length = models.IntegerField(blank=True, null=True)     ...

class Orange(Fruit):
    """orange (fruit type)"""
    diameter = models.IntegerField(blank=True, null=True)     ...

class FruitBasket(models.Model):
    fruits = models.ManyToManyField(Fruit)     ...

The problem I seem to be having is when I retrieve and inspect the Fruits in a FruitBasket, I only retrieve the Fruit base class and can't get at the Fruit child class attributes.

I think I understand what is happening--when the array is retrieved from the database, the only fields that are retrieved are the Fruit base class fields. But is there some way to get the child class attributes as well without multiple expensive database transactions? (For example, I could get the array, then retrieve the child Fruit classes by the id of each array element).

thanks in advance, Chuck

© Stack Overflow or respective owner

Related posts about django

Related posts about inheritance