Damiisdandy
Damiisdandy

Reputation: 397

Does for loop in Django models.py file affect performance?

I plan on using for loops to auto-generate a choices parameter for my field.

SIZE=[] # to be generated with a for loop to avoid me writing extra lines of code e.g (0, '32'),(1, '33')
...
old_price = models.PositiveIntegerField()
shoe_varient = models.IntegerField('SIZE', choices=SIZE)

Do for loops in the models.py file cause any performance issues, because I assume that the models.py file is just for the building (structuring) of the database.

In other words does the models.py file get called after every request?

Upvotes: 0

Views: 128

Answers (1)

pygeek
pygeek

Reputation: 7404

Solution

It would not necessarily affect performance as it is only run once, upon server start, when being loaded into memory. Choices also accepts method reference, which can be placed inside of the relevant model—this would possibly be a better approach to encapsulate the choices logic.

However, if you’re going through the trouble of hacking choices to be dynamic you’re probably better off creating a ForeignKey.

Note that choices can be any sequence object – not necessarily a list or tuple. This lets you construct choices dynamically. But if you find yourself hacking choices to be dynamic, you’re probably better off using a proper database table with a ForeignKey. choices is meant for static data that doesn’t change much, if ever.

References

Django Choices documentation: https://docs.djangoproject.com/en/3.1/ref/models/fields/#choices

Upvotes: 1

Related Questions