Django管理员在内联管理类中获取父模型的类名

时间:2013-04-16 13:18:57

标签: python django django-admin

以下是工作代码。我正在使用通用字段创建可以有多个图像的模型。我在管理方面使用内联。我需要一种方法来获取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)

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

parent_class = db_field.rel.to
parent_meta = parent_class._meta
app_label, object_name = parent_meta.app_label, parent_meta.object_name