Django inlinemodeladmin验证 - 但具有通用关系

EB.*_*EB. 7 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 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.')
Run Code Online (Sandbox Code Playgroud)

结果是,新的AssemblyAnnotation(通过内联附加)只能为其type属性提供值的子集,具体取决于父程序集.

这很有效.

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

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.')
Run Code Online (Sandbox Code Playgroud)

如您所见,我希望应用相同的规则.但是,有一个问题.我现在使用的GenericInline在运行clean()方法之前没有设置self.content_type.

有没有办法解决?我做错了吗?

谢谢您的帮助.

jef*_*upp 0

右侧不会返回一个列表吗 if self.content_type == ContentType.objects.get_for_model(Assembly):

我认为你需要做if self.content_type in ContentType.objects.get_for_model(Assembly):