Django many to many relation on generic models
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.
Take a look at the docs explaining the GenericInlineModelAdmin
.
If i get you right, the example does exactly what you want:
class Image(models.Model):
image = models.ImageField(upload_to="images")
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey("content_type", "object_id")
class Product(models.Model):
name = models.CharField(max_length=100)
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
:
class ImageInline(generic.GenericTabularInline):
model = Image
class ProductAdmin(admin.ModelAdmin):
inlines = [
ImageInline,
]
精彩评论