Does using Django model choices for search filters add server load on every page request?
I’m building a Django-based classifieds website.
Previously, my search form populated districts and categories using database queries like:
districts = (
AdPost.objects
.filter(admin_verified=True)
.values_list("district", flat=True)
.distinct()
)
To improve consistency and performance, I’ve now moved both district and category to static choices in the model.
Example:
class AdPost(models.Model):
CATEGORY_CHOICES = [
('fish', 'fish'),
('cow', 'cow'),
]
DISTRICT_CHOICES = [
('e', 'e'),
('j', 'j'),
]
category = models.CharField(max_length=50, choices=CATEGORY_CHOICES)
district = models.CharField(max_length=30, choices=DISTRICT_CHOICES)
In my view, I now pass these directly:
categories = AdPost.CATEGORY_CHOICES
districts = AdPost.DISTRICT_CHOICES
And render them in the search form:
<select name="district">
{% for key, label in districts %}
<option value="{{ key }}">{{ label }}</option>
{% endfor %}
</select>
Question
Does using model choices like this add any noticeable server load on every page request, or are these choices loaded once and reused?
I want to confirm that this approach is safe and efficient compared to querying the database on each request.
What I expect (but want confirmation)
My understanding is that:
choices are static Python data
They are loaded once when Django starts
Rendering them in templates does not cause database queries
Is this correct?
Environment
Django 4.x
PostgreSQL / SQLite
Standard class-based views
Вернуться на верх