H
H
Hadmi2020-05-11 18:45:13
Django
Hadmi, 2020-05-11 18:45:13

How to correctly change the field of the inherited model to a hard-coded value?

Good afternoon.

I have a base model from which I inherit other models, let's say:

class Base(models.Model):
    moveable = models.BooleanField(default=True, blank=False, null=False)
    abstract = models.BooleanField(default=False, blank=False, null=False)
    hidden = models.BooleanField(default=False, blank=False, null=False)


Further, for some inherited models, these properties must be hard-coded. For example, the "Equipment" model must have hardcoded values ​​moveable=True, abstract=False.
Now, actually, a question.
Is it possible to hard-code field values ​​when describing an inherited model, like this:
class Equipment(Base):
    moveable = True
    abstract = False
    ...
    ...


Or is it necessary to bother with prescribing values ​​when initiating class instances so as not to break the structure of the Django model?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
PashaWNN, 2020-05-11
@hadmi

You need to bother, because. the logic of reading/writing to the database is tied to the Field classes themselves, and so it will not work, but most likely an error will occur even when trying to create migrations due to the fact that the model field is redefined to a regular variable.
But it's better to get confused and think about the architecture, why did it lead to the need to hard-code field values ​​for child models. Perhaps the base class does not need these columns?
Django also supports things like abstract models, which don't create tables in the database at all, but only act as bases for other models. Most likely this is what you need.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question