[英]djongo RunPython in database migration
有一個 django 應用程序將 djongo 作為數據庫驅動程序。 我想使用RunPython
添加自定義遷移。 但我不明白如何到達 pymongo 客戶端。 這是代碼:
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),
]
你可以訪問 PyMongo:
schema_editor.connection.client_connection
的客戶端( MongoClient
實例)。schema_editor.connection.connection
的db ( Database
實例)。def _custom_migration(apps, schema_editor):
db = schema_editor.connection.connection
db.collection1.update_many({}, [{'$set': {"field2": "$field1.id"}}])
來源參考:
schema_editor.connection
包含DatabaseWrapper
實例。DatabaseWrapper.client_connection
包含MongoClient
實例。(Base)DatabaseWrapper.connection
包含Database
實例。來自文檔https://pymongo.readthedocs.io/en/stable/tutorial.html試試這個:
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"}}])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.