Django model class vs a dictionary for storing reference values

I'm fairly new to Django, and while creating a project, I've been going back and forth between using a fixed value dictionary for certain reference values, or using another model class which is referred using a Foreign Key field.

A part of the code using the model class option is as follows:

Models with reference values:

class MaterialCategory(models.Model):
    name = models.CharField(max_length=32, unique=True, help_text="A primary class of materials.")

    class Meta:
        verbose_name_plural = 'Material categories'
        constraints = [
            UniqueConstraint(
                Lower('name'),
                name='materialcategory_name_case_insensitive_unique',
                violation_error_message="Material category already exists in "
                                        "the database!"
            ),
        ]


class ComponentType(models.Model):
    """Model for key component types of a water supply scheme."""
    name = models.CharField(max_length=100, unique=True, help_text="Main categories of a water system")

    def __str__(self) -> str:
        return self.name

    class Meta:
        ordering = ["name", "id",]

An example model referring to above:

class Chlorinator(models.Model):
    """Model representing a chlorinator."""
    CHOICES_YES_NO = {"yes": "Yes", "no": "No", "na": "Not applicable"}
    CHLORINATOR_TYPES = {
        'cc' : 'Constant head chlorinator',
        'nc' : 'Simple tank (non-constant head)',
        'dp' : 'Chlorine dosing pump',
        'gc' : 'Gas chlorination system',
        'o' : 'Other',
    }

    id = models.UUIDField(
        primary_key=True, default=uuid.uuid4, help_text="Unique ID for the chlorinator instance",
    )

    component_type = models.ForeignKey(
        ComponentType, on_delete=models.RESTRICT,
        limit_choices_to=Q(name__istartswith='treatment'), default=''
    )

    chlorinator_type = models.CharField("Chlorinator type", max_length=2, choices=CHLORINATOR_TYPES)

    material = models.ForeignKey(
        Material, on_delete=models.RESTRICT, blank=True, null=True,
        limit_choices_to=Q(material_category__name__istartswith='composites')
    )

    def __str__(self) -> str:
        return f"{self.id} - {self.CHLORINATOR_TYPES[self.chlorinator_type]}"

    class Meta:
        ordering = ['chlorinator_type', 'id',]

There are another 10 or so models similar the this, all using the first two reference models.

Now, while I'm testing out those, I felt like I could've used a dictionary to store the 'Materials' and 'Component Types', and then referred to them in the later models. But I'm not sure if that is in someway not effective or poor design.

I would love to get someone's comment on which method is better, and if possible, why.

(The fixed value dictionary I mentioned would be a global dictionary)

Вернуться на верх