Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always treat a ForeignKey field like it was in raw_id_fields in Django Admin

This scenario happens way too often in my project:

  • someone adds a model Foo that has several ForeignKey fields, one of them to refers to model Bar
  • an admin is added for that model (and works OK)
  • the code is deployed
  • on production server, Bar has millions of instances
  • someone accesses Foo's admin page; Django tries to retrieve all Bars at once (to display them in a combo box) and the server gets overloaded
  • later the problem gets fixed by editing Foo's admin and adding bar to raw_id_fields.

I'd like to prevent this situation from happening in the future, preferably by somehow stating (once and for all) that Bar has many rows and it should be always treated as if the field referring to it was listed in raw_id_fields in all admin pages. Is this possible somehow?

like image 654
Kos Avatar asked Jun 25 '14 09:06

Kos


People also ask

What is Fieldsets in Django admin?

Set fieldsets to control the layout of admin “add” and “change” pages. fieldsets is a list of two-tuples, in which each two-tuple represents a <fieldset> on the admin form page. (A <fieldset> is a “section” of the form.)

How can I remove extra's from Django admin panel?

You can add another class called Meta in your model to specify plural display name. For example, if the model's name is Category , the admin displays Categorys , but by adding the Meta class, we can change it to Categories . Save this answer. Show activity on this post.

How do I show many to many fields in Django admin?

Yes, you can use list_display to display Many-to-Many fields in Django Admin.

Where is Django admin template?

The default templates used by the Django admin are located under the /django/contrib/admin/templates/ directory of your Django installation inside your operating system's or virtual env Python environment (e.g. <virtual_env_directory>/lib/python3. 5/site-packages/django/contrib/admin/templates/ ).


1 Answers

This is an excelent point. This is a critical issue that can turn down the database and even the web server.

Considering this, I believe the default approach MUST be the raw_id_fields thing. If you know what you are doing, then you change this behavior.

Unfortunately, most of the authors of the admin interfaces libraries disagree of this thought. Not just for Python-Django, but also for other communities like Ruby-Rails.

5 years ago I got tired having the same problem, then I developed the django-smart-autoregister, that do this and also auto configure using another good patterns. Even today I face this problem, so I guess it is worth to take a look.

ps: the library was originally implemented using a modular approach, though you just call some functions that will configure the raw_id_fields for you according to the model field.

like image 100
Paulo Cheque Avatar answered Oct 19 '22 05:10

Paulo Cheque