djongo
djongo copied to clipboard
How to make RunPython in database migration
One line description of the issue
I want to add custom migration using RunPython. How to reach pymongo client?
Python script
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),
]
There might be better ways, but this is how i write custom data migrations where i need to use pymongo methods:
def _custom_migration(apps, schema_editor):
MyModel = apps.get_model("myproject", "MyModel")
MyModel.objects.mongo_update_many({}, [{'$set': {"field2": "$field1.id"}}])
The model is set up like this:
from djongo import models
class MigrationDjongoManager(models.DjongoManager):
"""Enables using pymongo queries in migrations."""
use_in_migrations = True
class MyModel(models.Model):
objects = MigrationDjongoManager()
...