I have been having a problem where a Django server takes forever to return a response. When running with gunicorn in Heroku I get a timeout, so can't receive the response. If I run locally, it takes a while, but after some time it correctly shows the site.
Basically I have two models:
class Entry(models.Model):
#Some stuff charFields, foreignKey, TextField and ManyToMany fields
#Eg of m2m field:
tags = models.ManyToManyField(Tag, blank=True)
def getTags(self):
ret = []
for tag in self.tags.all():
ret.append(getattr(tag, "name"))
return ret
def convertToDict(self):
#for the many to many field I run the getter
return {'id': self.id, 'tags' : self.getTags(), ... all the other fields ... }
class EntryState(models.Model):
entry = models.ForeignKey(Entry, on_delete=models.CASCADE)
def convertToDict(self):
temp = self.entry.convertToDict()
temp['field1'] = self.field1
temp['field2'] = self.field1 + self.field3
return temp
Then I have a view:
def myView(request):
entries = list(EntryState.objects.filter(field1 < 10))
dictData = {'entries' : []}
for entry in entries:
dictData['entries'].append(entry.convertToDict())
context = {'dictData': dictData}
return render(request, 'my_template.html', context)
The way it was done, the dictData contains the information for all the entries that must be shown in the site. Then, this variable gets loaded into a javascript that will decide how to display the information.
The view gets stuck in the for loop when there's lots of entries with field1 < 10.
I was just wondering, what can be done to improve this approach. With +600 entries it already takes forever, enough for gunicorn to timeout.
In case it is relevant, I am using Django 4.0.3 and Python3. The data is used in the frontend by Alpine.js to render the site.