1

I am writing a very custom migration in django, and I would like to make it work with the

django-admin migrate --database databse_name

command. Since I am creating a custom cursor, the default won't work for me. Is there any reasonable way to make it work?

maniexx
  • 625
  • 1
  • 12
  • 28
  • Do you need to run migration on specified database? – Ernest Jul 17 '15 at 12:34
  • If I just want to do that once, I can just change the default in the config. But I would like my migration to work with that for the long term. As is, I think I need to make it crash by default, to prevent someone migrating the wrong database accidentally. – maniexx Jul 17 '15 at 13:00
  • I think [this answer](http://stackoverflow.com/a/14442569/5098707) may help you. – Ernest Jul 17 '15 at 13:08
  • @ErnestTen No, not at all. I am just trying to get the name of the database that was passed to migrate. It is already in my database_config.py, I just need my script to know which one. – maniexx Jul 17 '15 at 13:28
  • You can always extend the [`migrate`](https://github.com/django/django/blob/master/django/core/management/commands/migrate.py) and add your custom logic to it.. – karthikr Jul 17 '15 at 13:32
  • @karthikr Sure, but I was hoping there was a not-terrible way to do this. If I am to modify django, I can get by with just having to make this migration more manually each time. My use case is just not big enough. – maniexx Jul 17 '15 at 13:41
  • Are you looking for the `allow_migrate` method in the database router? https://docs.djangoproject.com/en/1.8/topics/db/multi-db/#allow_migrate – Wolph Jul 17 '15 at 13:42
  • Or possibly, providing hints to the database router: https://docs.djangoproject.com/en/1.8/howto/writing-migrations/ – Wolph Jul 17 '15 at 13:43
  • @Wolph This could possibly used to achieve what I want, but no. All I want is to make my custom cursor connect to the right databas when migrate is run with `--database ` – maniexx Jul 17 '15 at 13:46

2 Answers2

2

You can access it by using db.db_alias. Hope it helps!

2

It's "let's answer really old questions" time!

Below info taken from the current-as-of-now django 3.0 docs

Your migration function will take a second argument which is a SchemaEditor object. This gives you the database for your commands.

def forwards_func(apps, schema_editor):
    # We get the model from the versioned app registry;
    # if we directly import it, it'll be the wrong version
    Country = apps.get_model("myapp", "Country")
    db_alias = schema_editor.connection.alias
    Country.objects.using(db_alias).bulk_create([
        Country(name="USA", code="us"),
        Country(name="France", code="fr"),
    ])
Dustin Wyatt
  • 4,046
  • 5
  • 31
  • 60
  • 2
    Thanks, I've been waiting all those years! In all seriousness, this does seem like the correct answer. – maniexx Feb 13 '20 at 14:09