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),
]
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"}}])
You can reach PyMongo:
- client (
MongoClientinstance) fromschema_editor.connection.client_connection. - db (
Databaseinstance) fromschema_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.connectionholds theDatabaseWrapperinstance.DatabaseWrapper.client_connectionholds theMongoClientinstance.(Base)DatabaseWrapper.connectionholds theDatabaseinstance.
To reach the PyMongo client in a Django app with Djongo as the database driver, you can use the djongo package to connect to the database:
from django.db import migrations from djongo import DjangoClient
def _custom_migration(apps, schema_editor):
client = DjangoClient()
db = client['database_name']
db.collection1.update_many({}, [{'$set': {"field2": "$field1.id"}}])
class Migration(migrations.Migration):
operations = [
migrations.RunPython(_custom_migration),
]
Here, client is the PyMongo client, and db is a PyMongo database instance. The name of the database is specified in the ['database_name'] part.