1

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?

fceruti
  • 2,405
  • 1
  • 19
  • 28
  • I don't see a problem with that. Just define your method to account for the difference in media_content type (pic or video) and you should be OK; doesn't seem difficult at all. – JEEND0 May 04 '11 at 22:45

1 Answers1

1

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.

Alasdair
  • 298,606
  • 55
  • 578
  • 516