How to run migrations on specific database using call_command() in Django?

Question:

I’m just wondering what the correct syntax is for calling $ python manage.py migrate app_name --database db_name with the management.call_command() function at runtime.

So far, I have the following:

from django.core import management
from django.core.management.commands import migrate

# Migrate the core.contrib.dynamics if needed to the pre-specified database:
management.call_command(migrate.Command(), 'dynamics', '--database {}'.format(DB_NAME))

However, I get the following error at runtime when calling the above:

Cannot find a migration matching '--database default_node' from app 'dynamics'.

I’m 99% sure I’m probably calling the -- args incorrectly? Can anyone point me in the right direction with this?

The migrations for the dynamics app are as follows:

# Generated by Django 3.0.8 on 2020-07-02 14:28

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='ModelSchema',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=32, unique=True)),
                ('_modified', models.DateTimeField(auto_now=True)),
            ],
        ),
        migrations.CreateModel(
            name='FieldSchema',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=63)),
                ('data_type', models.CharField(choices=[('character', 'character'), ('text', 'text'), ('integer', 'integer'), ('float', 'float'), ('boolean', 'boolean'), ('date', 'date')], editable=False, max_length=16)),
                ('null', models.BooleanField(default=False)),
                ('unique', models.BooleanField(default=False)),
                ('max_length', models.PositiveIntegerField(null=True)),
                ('model_schema', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='fields', to='dynamics.ModelSchema')),
            ],
            options={
                'unique_together': {('name', 'model_schema')},
            },
        ),
    ]
Asked By: Micheal J. Roberts

||

Answers:

Considering you already ran the migrations, you can simply use

management.call_command('migrate', app_label='dynamics', database='dbname')
Answered By: Tiago Martins Peres