How to modify the way a ForeignKey field is render

2019-06-07 14:37发布

I have a Customer model which contains a ForeignKey to a Contact model.

I have over 100,000 contacts in my DB and when I load the admin page for a specific customer, the dropdown menu for the contact is getting populated with ALL of the contacts in the database. This has recently, due to its shear length, started causing my Firefox to crash while the admin page is loading.

Is there a way to either:

  1. replace the field with an integer field I can manually modify to the contact ID when necessary
  2. replace the dropdown menu with some alternative input method which won't crash the browser
  3. remove this input from the Customer admin page altogether

Thanks!

2条回答
We Are One
2楼-- · 2019-06-07 14:47

Sounds like specifying the contact field in raw_id_fields in your admin.py entry for the relevant model would sort you out. Docs are here.

PS. Surprised (but not that surprised) that FF gives out before your database server tanks...

查看更多
ら.Afraid
3楼-- · 2019-06-07 14:51

You can do any of the either of things you want to.

Simplest solution is the exclude the field from the admin. Just say so in the admin class.

You can change the field to be text input and display it's primary key rather than the item itself, by including it in the raw_id_fields of the admin class.

You can also replace the standard dropdown widget with the Auto complete text field input. Use the implemented widget, or other equivalents. - This is probably the solution you like the best.

You can also override the formfield_for_foreignkey method on the Admin model to customize the queryset that gets displayed in the foreign-key dropdown. You may want to checkout my implementation for displaying only the current User's (or subdomain's) added entities.

查看更多
登录 后发表回答