django-rest-frameworkmongoenginerestframeworkmongoengine

Django rest framework mongoengine update new field with default value


I'm using Django rest framework mongoengine after created few documents, if i want add a new field with default value. Is there any way to do that orelse i need to update with few custom function.

Note: I want to fetch the data with filter having a new field name. That time the field is not there. So i'm getting empty.


Solution

  • From what I understand, you are modifying a MongoEngine model (adding a field with a default value) after documents were inserted. And you are having issue when filtering your collection on that new field.

    Basically you have the following confusing situation:

    from mongoengine import *
    
    conn = connect()
    
    conn.test.test_person.insert({'age': 5})    # Simulate an old object
    
    class TestPerson(Document):
        name = StringField(default='John')    # the new field
        age = IntField()
    
    person = TestPerson.objects().first()
    
    assert person.name == "John" 
    assert Test.objects(name='John').count() == 0
    

    In fact, MongoEngine dynamically applies the default value when the field of the underlying pymongo document is empty but it doesn't account for that when filtering.

    The only reliable way to guarantee that filtering will work is to migrate your existing documents. If its only adding a field with a default value, you could do this with MongoEngine: TestPerson.objects().update(name='John')

    If you did more important/complicated changes to your document structure, then the best option is to get down to pymongo.

    coll = TestPerson._get_collection()
    coll.update({}, {'$set': {'name': 'John'}})