Reputation: 6557
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
Reputation: 43073
You can reach PyMongo:
MongoClient
instance) from schema_editor.connection.client_connection
.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:
schema_editor.connection
holds the DatabaseWrapper
instance.DatabaseWrapper.client_connection
holds the MongoClient
instance.(Base)DatabaseWrapper.connection
holds the Database
instance.Upvotes: 2
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