Django 通用模型上的多对多关系
我有一些模型需要与一些图像有多对多的关系。我不想单独创建每个关系,而是希望拥有一些可用于所有模型的通用模型关系。所以我创建了 Image 和 ImageItem 模型(我不确定我是否走在正确的轨道上..):
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
class Image(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='images')
class ImageItem(models.Model):
image = models.ForeignKey(Image)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
object = generic.GenericForeignKey('content_type', 'object_id')
我想做的是,每次创建新图像时,我想选择我想要的对象将此图像分配给。因此,在管理员中我需要了解以下内容:
Image: chicago_bulls.jpg
Selected model: Player
Selected:
Michael Jordan
Scotie Pippen
或者
Image: kobe_bryant.jpg
Selected model: Team
Selected:
Los Angeles Lakers
US National Team
我的模型设计正确吗?我也想使用 ModelMultipleChoiceField 来实现这一点,但我不知道如何做到这一点。
I have some models which will need to have many to many relation with some images. Instead of creating each relation individually, I want to have some generic model relations that I can use for all my models. So I've created Image and ImageItem models (I'm not sure if I'm on the right track..):
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
class Image(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='images')
class ImageItem(models.Model):
image = models.ForeignKey(Image)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
object = generic.GenericForeignKey('content_type', 'object_id')
What I want to do is, every time I create a new image, I want to select which objects I want to assign this image to. So into the admin I need to have something like:
Image: chicago_bulls.jpg
Selected model: Player
Selected:
Michael Jordan
Scotie Pippen
or
Image: kobe_bryant.jpg
Selected model: Team
Selected:
Los Angeles Lakers
US National Team
Is my model design correct? I also want to use ModelMultipleChoiceField for that but I couldn't figure out how to do that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
查看解释
GenericInlineModelAdmin
。如果我没理解错的话,这个例子完全符合你的要求:
它与你的设计有点不同,因为图像字段是模型的一部分,它为所有类型的其他(内容)对象/模型添加了通用关系。
这样您就可以使用已经提到的
InlineAdmins
通过管理界面简单地附加图像:Take a look at the docs explaining the
GenericInlineModelAdmin
.If i get you right, the example does exactly what you want:
It's a bit different from your design, as the image field is part of model that adds generic relations to all kind of other (content) objects/models.
That way you can simply attach images via the admin interface using the already mentioned
InlineAdmins
: