Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to make RunPython in database migration #656

Open
Axbry opened this issue Jan 24, 2023 · 1 comment
Open

How to make RunPython in database migration #656

Axbry opened this issue Jan 24, 2023 · 1 comment

Comments

@Axbry
Copy link

Axbry commented Jan 24, 2023

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
Copy link

KonRatt commented Aug 16, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants