Django GenericForiegnKey,为管理员指定 ContentTypes include/exclude
Django GenericForiegnKey, specify ContentTypes include/exclude for admin
如果我有一个 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")
如何创建包含或排除列表,models/ContentTypes 我想将其包含在管理表单中?
目前,我得到了大约 30 个模型(项目中的所有模型)的列表,而实际上我只想要其中大约 3 或 4 个模型
您可以在您的管理员中提供自定义 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
直接添加到 Prereq
中的 target_content_type
字段 class:
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")
Where conditions 可以是字典、Q
对象(如在过滤器中)或一些可调用的返回字典或 Q
对象。
如果我有一个 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")
如何创建包含或排除列表,models/ContentTypes 我想将其包含在管理表单中?
目前,我得到了大约 30 个模型(项目中的所有模型)的列表,而实际上我只想要其中大约 3 或 4 个模型
您可以在您的管理员中提供自定义 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
直接添加到 Prereq
中的 target_content_type
字段 class:
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")
Where conditions 可以是字典、Q
对象(如在过滤器中)或一些可调用的返回字典或 Q
对象。