I am building a block system with a base block model with each type of block a separate subclass like so:
class BlockType(models.Model):
''' Defines properties of a block '''
title = models.CharField(max_length=50)
class_name = models.CharField(max_length=50)
class Block(models.Model):
''' Implementation of the block '''
product = models.ForeignKey('product.Product', related_name='blocks')
block_type = models.ForeignKey('product.BlockType', related_name='used_blocks')
order = models.IntegerField(default=0)
class ImageBlock(Block):
''' An image block '''
image = models.CharField(max_length=255)
class TextBlock(Block):
''' A text block '''
text = models.TextField()
What I’d like to be able to do is:
b = product.blocks.all()
And instead of this being a list of Block objects. Being a list of relevant subclasses.
So if a product had a TextBlock and 2 ImageBlocks. The above would have returned a TextBlock object and 2 ImageBlocks rather than 3 Block objects.
I’m affraid you can’t do that. But the question is: why you want to do that?
Before continuing, i have another question: Did you know that modeling these “blocks” the way you did you will get 3 different tables (4 with the “BlockType” table) in your database? Is that what you want?
I don’t know what you are going to do with these models and how you want to use them, so i will give you some links i think can help you a lot. If you want, you could give us more information about what you are going to do with these models and why you want to have a single queryset with two different models so we can really help you.
This could help you: https://docs.djangoproject.com/en/dev/topics/db/models/#proxy-models
or this: https://docs.djangoproject.com/en/dev/topics/db/models/#abstract-base-classes
Hope it helps! If no, please add more info in order to help us understand your problem and try to give you an answer