I have a small django model with two fields. There is already data in the database for this model.
class MetaDataValue(Model):
metadata_id = models.ForeignKey(MetaData, on_delete=models.CASCADE,)
value = models.CharField('value', max_length=200,)
I need to add another field,
short_value = models.CharField('short_value', max_length=200,)
I know when I perform a migration, it will complain because I don't have a default value for the existing rows in the database.
Is there a way to set the default value for short_value
to the string in the value
field that already exists in the database/model?
I want to do this because I only need to create a different short_value
for about 20 rows in the database, and there is no universal default value for this field. I would rather not have something like 'fred' or 'default' in the short_value
field because some fields have numbers, some have text, some have a combination of numbers and text. I also thought of creating a property instead of another model field, but there isn't a simple way to convert the value
field into the short_value
field.
Thanks!
To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB.
Default field values automatically insert the value of a custom field when a new record is created. You can use a default value on a formula for some types of fields or exact values, such as Checked or Unchecked for checkbox fields. After you have defined default values: The user chooses to create a new record.
You would have to add blank=True as well in field definition. If the model field has blank=True, then required is set to False on the form field. Otherwise, required=True. Don't forget to reset and sync DB again after changing this.
You can simply add the field to the model and call:
python3 manage.py makemigrations
Django will prompt you to fill in a "one-off" default value for this. For example, if I run this on your model, I see:
You are trying to add a non-nullable field 'short_value' to metadatavalue without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option: 1
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
>>> 'default'
Migrations for 'app':
app/migrations/0002_metadatavalue_short_value.py
- Add field short_value to metadatavalue
(the boldface part is the things I wrote myself).
Here the rows will thus take the text default
as value.
The "one-off" value is not a default value that is specified for your models. It is just a value that is stored in the migration file, and added to rows that might already exist.
We can post-edit the migration file, and provide a default value for the column and then run a function that basically copies the value from another column to the new column, for example:
# Generated by Django 2.0.2 on 2019-02-24 19:45
from django.db import migrations, models
def copy_value_to_short_value(apps, schema_editor):
MetaDataValue = apps.get_model('app', 'metadatavalue')
db_alias = schema_editor.connection.alias
from django.db.models import F
MetaDataValue.objects.using(db_alias).all().update(
short_value=F('value')
)
class Migration(migrations.Migration):
dependencies = [
('app', '0001_initial_commit'),
]
operations = [
migrations.AddField(
model_name='metadatavalue',
name='short_value',
field=models.CharField(default='value', max_length=200, verbose_name='short_value'),
preserve_default=False,
),
migrations.RunPython(copy_value_to_short_value),
]
We thus define a function copy_value_to_short_value
that looks similar to a Django ORM query, and then we add the migrations.RunPython(copy_value_to_short_value)
to the tasks that should be done in the migration.
You should of course edit the migration file before running the migrations, since otherwise the migration appears in the django_migrations
table, and Django considers the migration as "done".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With