在django中处理通用关系的麻烦 [英] Trouble handling generic relationship in django
问题描述
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屋!