Last active
March 5, 2018 13:20
-
-
Save nenodias/ca11daf691e55b6606afe8a6dccaf973 to your computer and use it in GitHub Desktop.
Example DBRef
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import pdb | |
| from mongoengine import * | |
| from mongoengine.base import BaseDocument | |
| import json | |
| from json import JSONEncoder | |
| class MongoEncoder(JSONEncoder): | |
| def default(self, o): | |
| pdb.set_trace() | |
| if isinstance(o, BaseDocument): | |
| data = o.to_json() | |
| # might not be present if EmbeddedDocument | |
| o_id = data.pop('_id', None) | |
| if o_id: | |
| data['id'] = str(o_id['$oid']) | |
| data.pop('_cls', None) | |
| return data | |
| else: | |
| return JSONEncoder.default(self, o) | |
| connect('curso') | |
| class Perfil(Document): | |
| nome = StringField(required=True) | |
| created_at = DateTimeField() | |
| updated_at = DateTimeField() | |
| meta = { | |
| 'collection':'usuario' | |
| } | |
| class Usuario(Document): | |
| nome = StringField(required=True) | |
| idade = IntField() | |
| perfil = ReferenceField(Perfil) | |
| created_at = DateTimeField() | |
| updated_at = DateTimeField() | |
| meta = { | |
| 'collection':'usuario' | |
| } | |
| for u in Usuario.objects.all(): | |
| print('Usuario:') | |
| print(json.dumps(u, cls=MongoEncoder)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from pymongo import MongoClient | |
| from bson.dbref import DBRef | |
| from bson.objectid import ObjectId | |
| from pymongo.database import Database | |
| connection = MongoClient('localhost', 27017) | |
| db = Database(connection, "curso") | |
| usu = db.usuario | |
| u = usu.find_one() | |
| u['perfil'] = DBRef('perfil', ObjectId('5a97edb521716605af431bc2')) | |
| usu.save(u) | |
| print(db.dereference(u['perfil'])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment