I have a million lines of data on my website. I am very waiting when I want to reach this page via admin. Maybe 40-50 seconds. I did the pagination 20, but nothing changed. Currently the default is 100.
Its my admin code
@admin.register(PollVote)
class PollVoteAdmin(admin.ModelAdmin):
list_display = ['poll','referer','vote','ip', 'created_date']
ordering = ('-created_date',)
search_fields = ['ip']
raw_id_fields = ['poll']
What can I do to speed up this page in Admin?
PollVote model:
class PollVote(models.Model):
poll = models.ForeignKey(Poll,on_delete=models.CASCADE,verbose_name="Poll Name",related_name="votes")
author = models.CharField(max_length=150,blank=True,verbose_name="Username")
vote = models.TextField(verbose_name='Vote')
ip = models.GenericIPAddressField(protocol="IPv4")
cookie = models.TextField(verbose_name="Voters' Cookie")
votecount = models.IntegerField(verbose_name="Vote Count",default=1,blank=True)
created_date = models.DateTimeField(auto_now_add=True,verbose_name="Created Date")
country_code = models.CharField(max_length=10,blank=True,verbose_name="Country Code")
country = models.CharField(max_length=50, blank=True, verbose_name="Country")
city = models.TextField(max_length=50, blank=True, verbose_name="City")
vote_duration = models.FloatField(default=0, verbose_name="Vote Duration")
referer = models.TextField(verbose_name='Referer', blank=True)
def __str__(self):
return self.author
class Meta:
ordering = ['poll']
This is likely because of an N+1 problem where it first will retrieve all the PollVote
objects, and then it has to make N queries to load the poll
s.
We can use the list_select_related
[Django-doc] option to add these to the .select_related(…)
[Django-doc] items that will then be fetched in the same query:
@admin.register(PollVote)
class PollVoteAdmin(admin.ModelAdmin):
list_display = ['poll', 'referer', 'vote', 'ip', 'created_date']
ordering = ('-created_date',)
search_fields = ['ip']
raw_id_fields = ['poll']
list_select_related = ['poll']