Ok, so I wan’t to create a forum app like this:
class Section(models.Model):
section_name = models.CharField(max_length = 200)
class Thread(models.Model):
title = models.CharField(max_length = 200)
content = models.TextArea()
But, I want 4 types of Thread where user can submit text or link or image or link that only contains image. content field will change depending on the types. What is the best approach to do this? Do i need to define SubThread for each type? or can i define like this:
class Thread(models.Model):
THREAD_TYPE = (
('text', 'Text'),
('link', 'Link'),
('imge', 'Image'),
('limg', 'Link Image'),
)
type = models.CharField(max_length = 4, choices = THREAD_TYPE)
title = models.CharField(max_length = 200)
if self.type == 'text':
content = models.CharField(max_length = 200)
# and so on...
Thank you.
You definitely cannot make fields conditional; think about how that would (or wouldn’t) work in the database.
Creating a sub-class of Thread for each type is an option, but you would have to use GenericForeignKeys to create a relationship between a Thread sub-class and another model. GenericForeignKeys don’t perform as well, if extremely high performance is a major consideration.
Another option would be to define Thread to support all your types (eg has FileField, URLField) and include a field with choices for the different types. Using the type field, you could specify a template to render the item and/or you could filter by type.