djangodjango-migrationsdjongo

djongo RunPython in database migration


There's a django app with djongo as database driver. I want to add custom migration using RunPython. But I can't understand how to reach pymongo client. Here's the code:

from django.db import migrations


def _custom_migration(apps, schema_editor):
    db = ... # what to put here?
    db.collection1.update_many({}, [{'$set': {"field2": "$field1.id"}}])


class Migration(migrations.Migration):
    operations = [
        migrations.RunPython(_custom_migration),
    ]

Solution

  • You can reach PyMongo:

    def _custom_migration(apps, schema_editor):
        db = schema_editor.connection.connection
        db.collection1.update_many({}, [{'$set': {"field2": "$field1.id"}}])
    

    Source references: