0

下面是一个工作代码。我正在使用通用字段创建可以具有多个图像的模型。我在管理员端使用内联。我需要一种在 inlineAdmin 类中获取模型(可以有多个图像)类名的方法,以使该系统更具可移植性...

#model mediaalbums
class MediaAlbum(models.Model):
    content_type = models.ForeignKey(ContentType, null=True, blank=True)
    media_type = models.CharField(max_length=5, choices= MEDIA_TYPE_CHOICES ) 
    name = models.CharField(unique = True, max_length=50)

class ModelImage(Media): 
    album = models.ForeignKey(MediaAlbum, null=True, blank=True, limit_choices_to = {'media_type': 'image'})
    file = ImageField(upload_to=get_path) 
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id') 

#model sections
class Work(models.Model):
    images = generic.GenericRelation(ModelImage)

#admin
class ModelImageInline(generic.GenericStackedInline):
    model = ModelImage
    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        field = super(ModelImageInline, self).formfield_for_foreignkey(db_field, request, **kwargs)
        if db_field.name == 'album':
                # for now i am getting the model's (that can have any number of images )           class name from the model's admin class' request object
                # but i do not want to get it from there
                className = request.className
                field.queryset = field.queryset.filter(content_type__name=className)    #building__exact = request._obj_
        return field


class WorkAdmin(TranslationAdmin):
    inlines = [ModelImageInline ]
    def get_form(self, request, obj=None, **kwargs):
        # pass the class name to inline class
        request.className = 'work'
        return super(WorkAdmin, self).get_form(request, obj, **kwargs)
4

2 回答 2

4

答案: self.parent_model.__name__ 在内联类中使用。

于 2013-04-17T13:28:47.467 回答
1
parent_class = db_field.rel.to
parent_meta = parent_class._meta
app_label, object_name = parent_meta.app_label, parent_meta.object_name
于 2013-04-16T22:16:22.477 回答