I
I
Igor2019-03-25 23:58:51
Django
Igor, 2019-03-25 23:58:51

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?

Code with choices
#...
class Item(models.Model):
    #...
    UNIT = (
        ("кг", "килограммы"),
        ("м", "метры"),
        ("мм", "миллиметры")
    )
    #...
    unit = models.CharField(choices = UNIT)
    #...
Code with ForeignKey
#...
class Item(models.Model):
    #...
    unit = models.ForeignKey("Unit")
    #...

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry, 2019-04-06
@Igorello74

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.

O
OnYourLips, 2019-03-26
@OnYourLips

Premature denormalization is an antipattern.
Judging by your task description, you need a ForeignKey, just greedily pull up the related entity.

A
alternativshik, 2019-03-26
@alternativshik

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 question

Ask a Question

731 491 924 answers to any question