Search code examples
pythondjangodjango-contenttypes

Django GenericForiegnKey, specify ContentTypes include/exclude for admin


If I have a 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")

How can I create an include or exclude list for which models/ContentTypes I want included in the admin form?

Currently, I get a list of about 30 models (all the models in the project), when really I only want about 3 or 4 of those models

enter image description here


Solution

  • You can provide custom ModelForm on your admin and limit queryset inside target_content_type field.

    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
    

    Also you can add limit_choices_to directly into your target_content_type field in Prereq 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 can be an dictionary, Q object (like in filter) or some callable returning dictionary or Q object.