Django inlinemodeladmin验证-但具有泛型关系

Django inlinemodeladmin验证-但具有泛型关系,django,django-admin,models,Django,Django Admin,Models,我以前有过这样的模型: class AssemblyAnnotation(models.Model): assembly = models.ForeignKey(Assembly) type = models.ForeignKey(AssemblyAnnotationType) ... def clean(self): from django.core.exceptions import ValidationError if not

我以前有过这样的模型:

class AssemblyAnnotation(models.Model):
    assembly = models.ForeignKey(Assembly)
    type = models.ForeignKey(AssemblyAnnotationType)
    ...
    def clean(self):
        from django.core.exceptions import ValidationError
        if not self.type.can_annotate_aliases and self.assembly.alias_of_id is not None:
            raise ValidationError('The selected annotation type cannot be applied to this assembly.')
其效果是,新的AssemblyAnnotation(通过内联连接)只能具有其类型属性的一个子集值,具体取决于父程序集

这很有效

现在,是时候将这些注释应用于稍微不同的其他对象了:

class ObjectAnnotation(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey()
    type = models.ForeignKey(AssemblyAnnotationType)
    ...
    def clean(self):
        from django.core.exceptions import ValidationError
        if self.content_type == ContentType.objects.get_for_model(Assembly):
            if not self.type.can_annotate_aliases and self.content_object.alias_of_id is not None:
                raise ValidationError('The selected annotation type cannot be applied to this assembly.')
正如你所看到的,我希望应用相同的规则。然而,有一个问题。在运行clean()方法之前,我现在使用的GenericInline没有设置self.content\u类型

这有什么办法吗?我做错了吗


谢谢你的帮助。

右手边不是会返回列表吗
如果self.content\u type==ContentType.objects.get\u for\u model(Assembly):


如果self.content\u在ContentType.objects.get\u中键入,我认为您需要执行
。\u模型(程序集):

我使用与您相同的工具,它可以正常工作。这是我的密码:

在模型中:

class GroupFlagIntermediate(models.Model):
    group_flag = models.ForeignKey(GroupFlag, related_name='flag_set')
    content_type = models.ForeignKey(ContentType, verbose_name='Flag Type')
    flag_pk = models.CharField('Flag PK', max_length=100, blank=True, default='')
    flag = generic.GenericForeignKey('content_type', 'flag_pk')

    def clean(self):
        from django.core.exceptions import ValidationError
        if not self.is_valid_flag(self.content_type.model_class()):
            raise ValidationError('The selected flag is not a real Flag.')
在管理中:

class GroupFlagIntermediateInline(admin.TabularInline):
    model = GroupFlagIntermediate

class GroupFlagAdmin(admin.ModelAdmin):
    list_display = ('name', ...)
    inlines = [GroupFlagIntermediateInline]

admin.site.register(GroupFlag, GroupFlagAdmin)
经过一些测试,我发现在clean()调用之前设置了
content\u type
object\u id
flag\u pk
)字段,但是
GenericForeignKey
flag
)没有设置。

否,获取\u模型。无论如何,这不是问题所在。问题是GenericInline在调用clean()之前没有设置内容类型。