T
T
TitanFighter2015-09-12 22:57:50
Django
TitanFighter, 2015-09-12 22:57:50

Is it possible, is it worth it and if “yes”, then how ... in the model, in addition to the field, immediately indicate the possible values ​​\u200b\u200bof this field and write them to the database during migration?

Good afternoon.
For example, there is

class Country(models.Model):
    country_name = models.CharField('Country', max_length = 30)

and i know that in db i need only 3 countries, let's say ireland, hungary and turkey. As far as I understand, only tables and fields are created during migration.
Questions:
1) Is it possible ...
2) Is it worth it ...
3) and if "yes", then how ... when migrating a model, write data to the database immediately?
Thank you.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dimonchik, 2015-09-12
@dimonchik2013

https://docs.djangoproject.com/en/1.8/ref/models/f...
see choices

S
sim3x, 2015-09-12
@sim3x

you can
https://docs.djangoproject.com/en/1.8/ref/models/f...
it's worth it - the question is to support the normal form of the database
if necessary, and write in the migration the data necessary for the application to work

O
Oleg, 2015-09-15
@Bahusss

So, as you already found out, choices are not written to the database - they are stored exclusively in the code and are used by the ORM to validate data and form a list of options in forms, for example, in the Django admin panel.
When the task is set, the following comes to mind:
Use choices and store a list of countries in the project settings - Django settings, this way it will be easier to use the Django ORM features for data validation and data submission in forms. It is worth considering that when adding a new country, you will have to change the settings and restart (reroll) the project.
Then, write the datamigrationto add the countries you need to the database. In such a migration, you can cycle through the country names from the project settings and create all the necessary objects if they have not already been created.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question