Trouble handling generic relationship in django

一笑奈何 提交于 2019-12-24 11:12:51

问题


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?


回答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.



来源:https://stackoverflow.com/questions/5890559/trouble-handling-generic-relationship-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!