Answer the question
In order to leave comments, you need to log in
Choices or ForeignKey: which one to use?
Good afternoon! Tell me, please, kind people, what is better to use: choices or ForeignKey ? Let's imagine the situation, the Item object (thing) has a unit field ( unit), how should I make it?
If I do with choices , then, as for me, it will be inconvenient to edit the name of an existing unit of measure or add a new one.
If I do it with a ForeignKey , then it seems to me that performance will decrease due to additional requests to the database.
Can you please tell me which of the two evils is the lesser?
#...
class Item(models.Model):
#...
UNIT = (
("кг", "килограммы"),
("м", "метры"),
("мм", "миллиметры")
)
#...
unit = models.CharField(choices = UNIT)
#...
#...
class Item(models.Model):
#...
unit = models.ForeignKey("Unit")
#...
Answer the question
In order to leave comments, you need to log in
If you think that you will be changing or adding units of measure quite often, then use ForeignKey. In terms of performance, add prefetch_related to queries , a very good thing, + 1 query will not affect performance in any way. But there are also some nuances that need to be taken into account.
Premature denormalization is an antipattern.
Judging by your task description, you need a ForeignKey, just greedily pull up the related entity.
I personally don’t see any reason to keep choices in the database if they are constant and the maximum is that in a year you will add kilometers there ...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question