doableware / djongo

Django and MongoDB database connector
https://www.djongomapper.com
GNU Affero General Public License v3.0
1.88k stars 355 forks source link

How to make RunPython in database migration #656

Open Axbry opened 1 year ago

Axbry commented 1 year ago

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),
    ]
KonRatt commented 1 year ago

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()
    ...