Opened 4 years ago

Last modified 21 months ago

#17881 new New feature

Implement BaseModelAdmin.get_raw_id_fields, similar to get_readonly_fields

Reported by: aaugustin Owned by: nobody
Component: contrib.admin Version: 1.4-beta-1
Severity: Normal Keywords: raw_id_fields
Cc: kmike84@… Triage Stage: Accepted
Has patch: yes Needs documentation: yes
Needs tests: yes Patch needs improvement: no
Easy pickings: no UI/UX: no


In order to prevent massive drop downs for related fields when the related model has lots of items, I'd like to add such fields automatically to raw_id_fields.

I've managed to make them read only by implementing the following get_readonly_fields method in the base class that all my ModelAdmin classes inherit:

    # ...

class ModelAdmin(admin.ModelAdmin):

    def get_readonly_fields(self, request, obj=None):
        explicit_readonly_fields = super(ModelAdmin, self).get_readonly_fields(request, obj)
        automatic_readonly_fields = self.related_fields_with_too_many_instances()
        return tuple(set(explicit_readonly_fields) | set(automatic_readonly_fields))

    def related_fields_with_too_many_instances(self):
        fields = []
        for f in self.model._meta.fields:
            # If the field isn't shown anyway, don't bother.
            if self.fields and not in self.fields:
            # If we made the field editable by id, that means we want to edit it, even if it's impractical
            if in self.raw_id_fields:
            # If the field is a ForeignKey to a blacklisted model, make it read only.
            if isinstance(f, (django_models.ForeignKey, django_models.ManyToManyField)):
                related_model = '%s.%s' % (,
                if related_model in MODELS_WITH_TOO_MANY_INSTANCES_FOR_ADMIN_SELECT:
        return fields

However, power users occasionally complain that they can no longer edit these fields... which is why I'd like a get_raw_id_fields method that I could override.

Attachments (1)

17881-poc.patch (2.0 KB) - added by aaugustin 4 years ago.

Download all attachments as: .zip

Change History (7)

comment:1 Changed 4 years ago by aaugustin

  • Has patch set

I'm uploading an untested patch showing the idea.

It'd be nice if get_raw_id_fields accepted an optional obj argument, but apparently, this information isn't available in the formfield_for_* methods. This needs more investigation.

Changed 4 years ago by aaugustin

comment:2 Changed 4 years ago by julien

  • Needs documentation set
  • Needs tests set
  • Triage Stage changed from Unreviewed to Accepted

comment:3 Changed 4 years ago by kmike

  • Cc kmike84@… added

comment:4 Changed 21 months ago by collinanderson

  • Keywords raw_id_fields added

comment:5 Changed 21 months ago by collinanderson

  • Keywords raw-id-fields added; raw_id_fields removed

comment:6 Changed 21 months ago by collinanderson

  • Keywords raw_id_fields added; raw-id-fields removed
Note: See TracTickets for help on using tickets.
Back to Top