StuffHappens
StuffHappens

Reputation: 6557

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),
    ]

Upvotes: 1

Views: 159

Answers (2)

aaron
aaron

Reputation: 43073

You can reach PyMongo:

  • client (MongoClient instance) from schema_editor.connection.client_connection.
  • db (Database instance) from schema_editor.connection.connection.
def _custom_migration(apps, schema_editor):
    db = schema_editor.connection.connection
    db.collection1.update_many({}, [{'$set': {"field2": "$field1.id"}}])

Source references:

Upvotes: 2

Blayne
Blayne

Reputation: 26

from documentation https://pymongo.readthedocs.io/en/stable/tutorial.html try this:

from pymongo import MongoClient

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

Upvotes: 0

Related Questions