How to optimize django admin using request cache

im trying to optimize dbase requests from the administrator by caching the results and using incoming requests. But - I still see a dbase request for each entry.

I have a model like this:

class actions(models.Model): user = models.ForeignKey(MyUser) action = ... class Myuser(Models.Model): name = models.CharField() company = models.ForeignKey(Companies) 

in admin change_list, I would like to see a table with:

 user action company_name 

so I defined my admin as follows:

 class ActionsAdmin(admin.ModelAdmin): list_display = ('user','action','company_name') ... def company_name(self,instance): return instance.user.company 

When I run this, I see that for each user there is a request to the company model to retrieve the company name. However, since there are not many companies, and in many cases, users perform many actions once in a row, I want to query for all companies once, and then use the cached result instead of accessing the database for each record.

How can i do this?

+4
source share
1 answer

Use list_select_related to indicate the relationship to the selection with the query, so in your case:

 class ActionsAdmin(admin.ModelAdmin): list_display = ('user','action','company_name') list_select_related = ('user__company', ) ... def company_name(self,instance): return instance.user.company 

Edit:

You can also point the field directly to list_display , without requiring a special method.

It should handle list_select_related for you (at least according to the docs linked above). If your Companies model is assumed to have a name field:

 class ActionsAdmin(admin.ModelAdmin): list_display = ('user','action','user__company__name') 
+6
source

Source: https://habr.com/ru/post/1494632/


All Articles