Django Models with default value in another branch

Asked

Viewed 90 times

1

I have a field that I added to another branch (which has status developing) calling for money, with default value: 0.00 in the model User. However, it is not yet being used in the production branch.

Today when I went to take a test to create an account, I received the following error:

IntegrityError at /users/register
(1364, "Field 'money' doesn't have a default value")

I realized that in my Mysql is still the field money created in another branch. However, in the database it does not have a default value.

class User(AbstractUser):
    ...
    money = models.DecimalField(max_digits=8, decimal_places=2, null=True, default=0.00)

I would like to understand why Django did not set to default 0.00 in Mysql. This is causing a problem when creating accounts, but it should not because a default value has been created. Django manually does the default value?

1 answer

1


Django actually sets the default value by code. I believe the reason for this is because it is possible to pass a function to the value default, something that would not be feasible to do in a generic way for all databases.

About your problem, ideally you should recreate your database when changing branches, as this would ensure that your database is in line with the current implementation, this avoids a lot of headache.

  • It is complicated to recreate the database, it is one more concern because that is not how I will act in production. I also had problems passing functions that generate random tokens in the default. He understood it as a different value every time I did Migrations. I did what I did in those token cases, I leave the field null=True and in custom save I define a value. This solves my problem.

  • 1

    In production you will use the migrations, they serve to ensure that the data structure is correct, and ideally this would be done by an automated CI/CD process, where this field scenario created in the database that does not have mapping in the ORM is impossible to happen. An alternative to prevent the destruction of the local database is to reverse the migrations before switching from the development branch.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.