在django中处理通用关系的麻烦 [英] Trouble handling generic relationship in django

查看:117
本文介绍了在django中处理通用关系的麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想模拟一个情况,我处理它真的很麻烦。域名是这样的:有帖子,每个帖子都必须与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

 code> class Post(models.Model):
...
#link to MediaContent
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField )
media_content = generic.GenericForeignKey('content_type','object_id')

最终想要做,可以调用方法,如:

  post1.media_content.draw_item()
> > < iframe src =youtube.com...>
post2.media_content.draw_item()
>> < img src =.../>

这是正确的aproach,它是否正常工作?模板可以与下面的对象无关吗?

解决方案

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

  {%在帖子中的帖子%} 
{{post.media_content.draw_item} }
{%endfor%}

无论哪个模型是通用的外国人要点,只要它有一个 draw_item 方法定义。


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?

解决方案

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.

这篇关于在django中处理通用关系的麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆