hmarr / mongoengine

[Moved to mongoengine/mongoengine]
https://github.com/MongoEngine/mongoengine
MIT License
795 stars 20 forks source link

Declaring a primary key causes empty ListFields to not be saved #428

Open roysmith opened 12 years ago

roysmith commented 12 years ago

This is one is really weird. It looks like if you declare a field to be a primary key, other ListFields which are empty don't get saved. When I run the test case appended below, I get:

[]
[]
{u'_id': ObjectId('4f36d01064a0d613ff000000'), u'l': []}
{u'_id': 1}

The two classes are identical other than one having a primary key and the other not. This behavior is really mystifying (and is causing us to write defective objects into our database). I'm assuming this is a bug, and not some subtle behavior that's supposed to be happening.

#!/usr/bin/env python                                                                                                              

import pymongo

from mongoengine import *
import mongoengine

mongo = pymongo.Connection()
mongoengine.connect('test')

class Play1(Document):
    meta = {'allow_inheritance' : False}
    l = ListField(IntField(), default=list)

class Play2(Document):
    meta = {'allow_inheritance' : False}
    l = ListField(IntField(), default=list)
    _id = IntField(primary_key=True)

Play1.objects.delete()
Play2.objects.delete()

p1 = Play1()
p2 = Play2(id=1)

# Here, both p1 and p2 will show empty lists for "l"                                                                               
print p1.l
print p2.l

p1.save()
p2.save()

# Here, only p1 will have an "l" field!                                                                                            
print mongo.test.play1.find_one()
print mongo.test.play2.find_one()
dangoldin commented 12 years ago

I'm seeing the same thing happen - pretty odd but it doesn't really effect the behavior since it will default to an empty list when read.