Reputation: 397
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
Reputation: 7404
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.
Django Choices documentation: https://docs.djangoproject.com/en/3.1/ref/models/fields/#choices
Upvotes: 1