Reputation: 544
im trying to optimize dbase queries from the admin, by caching the results and using in coming queries. But - i still see 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 the admin change_list, i'd 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 query to the company model to extract the company's name. However, since there are not many companies and in many cases, users perform many actions once after the other, i want to query for all companies once and then use the cached result instead of accessing the dbase for each entry.
How can i do that?
Upvotes: 4
Views: 2950
Reputation: 1846
Use list_select_related to specify the relation to select 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 specify the field directly on list_display
, without the need for custom method.
It should handle list_select_related
for you (at least according to the docs linked above). If assuming your Companies
model has a name
field:
class ActionsAdmin(admin.ModelAdmin):
list_display = ('user','action','user__company__name')
Upvotes: 6