Django GenericForiegnKey,为admin指定ContentTypes include / exclude

时间:2015-08-30 07:24:13

标签: python django django-contenttypes

如果我有GenericForeignKey

class Prereq(models.Model):
    target_content_type = models.ForeignKey(ContentType, related_name='prereq_parent')
    target_object_id = models.PositiveIntegerField()
    target_object = GenericForeignKey("target_content_type", "target_object_id")

如何为管理表单中包含哪些型号/内容类型创建包含或排除列表?

目前,我得到了一个大约30个模型的列表(项目中的所有模型),当我真的只需要大约3或4个模型时

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以在管理员处提供自定义ModelForm,并限制target_content_type字段内的查询集。

class PrereqAdminForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(PrereqAdminForm, self).__init__(*args, **kwargs)

        self.fields['target_content_type'].queryset = ContentType.objects.filter(your_conditions='something')

class PrereqAdmin(admin.ModelAdmin):
    form = PrereqAdminForm

您也可以将limit_choices_to直接添加到target_content_type课程的Prereq字段中:

class Prereq(models.Model):
    target_content_type = models.ForeignKey(ContentType, related_name='prereq_parent', limit_choices_to=conditions)
    target_object_id = models.PositiveIntegerField()
    target_object = GenericForeignKey("target_content_type", "target_object_id")

条件可以是字典,Q对象(如过滤器中)或某些可调用的返回字典或Q对象。