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:

我想模拟一个情况,我在处理它时遇到了麻烦。域名是这样的:有帖子,每个帖子必须与MediaContent一对一关联。 MediaContent可以是图片或视频(现在,可能是以后的音乐)。所以,我所拥有的是:

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 个解决方案

#1


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

你的方法对我来说很好。您只需要覆盖图片和视频模型中的draw_item方法。你的模板看起来像

{% 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.

并且通用外键指向哪个模型并不重要,只要它定义了draw_item方法。

更多相关文章

  1. Django代理模型返回父模型
  2. Tensorflow:恢复图形和模型,然后在单个图像上运行评估
  3. 集成erlang和python的最佳方法
  4. python中查看变量内存地址的方法
  5. [caffe(二)]Python加载训练caffe模型并进行测试2
  6. RHEL6误安装RHEL7的包导致glibc被升级后系统崩溃处理方法
  7. Linux selinux关闭方法和防火墙关闭方法
  8. Linux系统下Tar文件安装方法
  9. linux shell脚本编程笔记(四): 获取字符串长度的七种方法

随机推荐

  1. telnet登录Linux上报Login incorrect
  2. Java锁机制了解一下
  3. 使用docker compose 安装zookeeper、kafk
  4. 文章目录导航
  5. Android(安卓)-- Vold机制简要分析
  6. Thread源码剖析
  7. ConcurrentHashMap基于JDK1.8源码剖析
  8. 四种常量的解释
  9. 组合模式在开源代码中的应用
  10. Set集合就这么简单!