Reputation: 2445
I want to model a situation and I´m having real trouble handling it. The domain is like this: There are Posts, and every post has to be associated one to one with a MediaContent. MediaContent can be a picture or a video (for now, maybe music later). So, what I have is:
mediacontents/models.py
class MediaContent(models.Model):
uploader = models.ForeignKey(User)
title = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True)
def draw_item(self):
pass
class Meta:
abstract = True
class Picture(MediaContent):
picture = models.ImageField(upload_to='pictures')
class Video(MediaContent):
identifier = models.CharField(max_length=30) #youtube id
posts/models.py
class Post(models.Model):
...
# link to MediaContent
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
media_content = generic.GenericForeignKey('content_type', 'object_id')
What i eventually want to do, is beeing able to call methods like:
post1.media_content.draw_item()
>> <iframe src="youtube.com" ...>
post2.media_content.draw_item()
>> <img src="..."/>
Is this the correct aproach, does it work? Can the template be agnostic of the object underneath?
Upvotes: 1
Views: 126
Reputation: 308799
Your approach looks good to me. You just need to override the draw_item method in your Picture and Video models. Your template will look something like
{% for post in posts %}
{{ post.media_content.draw_item }}
{% endfor %}
and it doesn't matter which model the generic foreign key points to, as long as it has a draw_item
method defined.
Upvotes: 1