[Fixed]-Django GenericForiegnKey, specify ContentTypes include/exclude for admin

1👍

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.

Leave a comment