Emanuel Ey
Emanuel Ey

Reputation: 2844

What can cause failure to store an `int` to an `IntField`?

I have the following MongonEngine models:

from app import db
from datetime import datetime
from mongoengine import signals


class PathEmbedded(db.EmbeddedDocument):
    """
        To be embedded.
    """

    _id = db.ObjectIdField(required=False)
    distance = db.IntField(required=False, min_value=0, default=0)
    meta = {
        "allow_inheritance": True,
    }

    def __unicode__(self):
        return "Path '%s': %d m" % (self.id, self.distance)


class Path2(PathEmbedded, db.Document):
    """
        Same as above, but standalone version to be stored in its own collection.
    """

    _id = db.ObjectIdField()
    orig = db.ObjectIdField(required=True)
    dest = db.ObjectIdField(required=True)
    updateStamp = db.DateTimeField(required=True)
    ok_to_use = db.BooleanField(required=True, default=False)
    meta = {
        'indexes': [
            {
                'fields': ['ok_to_use', 'orig', 'dest'],
                'cls': False,       # does this affect performance?!
            },
        ],
    }

    @classmethod
    def pre_save(cls, sender, document, **kwargs):
        document.updateStamp = datetime.utcnow()

    def to_embedded(self):
        """
            Converts the standalone Path instance into an embeddadle PathEmbedded instance.
        """

        import json
        temp = json.loads(self.to_json())

        #remove the {"_cls": "Location"} key.
        #If we don't do this, the output will be a 'Location' instance, not a 'LocationEmbedded' instace
        temp.pop('_cls')

        return PathEmbedded().from_json(json.dumps(temp))



    def get_from_gmaps(self):
        """
            Get distance from Google maps using the directions API and append to the 'paths' list.
            Return False on error or True on success.
        """

        try:
            self.distance = 10,
            self.save()

        except Exception, e:
            print str(e)
            return False

        else:
            return True

# connect event hooks:
signals.pre_save.connect(Path2.pre_save, sender=Path2)

So, at some point I'm updating a path instance by calling get_from_gmaps():

from app.models.Path2 import Path2 as P
from bson import ObjectId

p=P(orig=ObjectId(), dest=ObjectId())
p.save()
p.get_from_gmaps()

which raises:

>>> p.get_from_gmaps()
ValidationError (Path2:54d34b97362499300a6ec3be) (10 could not be converted to int: ['distance'])
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "[...]app/models/Path2/get_from_gmaps.py", line 18, in get_from_gmaps
    self.save()
  File "[...]venv/local/lib/python2.7/site-packages/mongoengine/document.py", line 224, in save
    self.validate(clean=clean)
  File "[...]venv/local/lib/python2.7/site-packages/mongoengine/base/document.py", line 323, in validate
    raise ValidationError(message, errors=errors)
ValidationError: ValidationError (Path2:54d34b97362499300a6ec3be) (10 could not be converted to int: ['distance'])

Originally I was storing an integer parsed from some json and converted to int, and thought somthing was wrong there, but i replaced it with an int value for debugging and now get this. I really don't know where to start o.O

EDIT: expanded code to provide complete [non]working example.

Upvotes: 1

Views: 417

Answers (2)

Andrea Corbellini
Andrea Corbellini

Reputation: 17751

There's an extra comma after the 10:

self.distance = 10,
                  ^

You are setting distance to a tuple containing an int, instead of an int.


HINT: The reason why your are seeing such an unhelpful message is that MongoEngine is using %s format string improperly. In fact, the result of "%s" % something depends on the type of something, as tuples are special cased. Compare:

>>> '%s' % 10
'10'
>>> '%s' % (10,)
'10'
>>> '%s' % (10, 11)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
>>> '%s' % ((10,),)  # This is the correct way of formatting strings
'(10,)'              # when the type of the argument is unknown.

This is a MongoEngine's problem of course, but if you want to avoid the same kind of mistake in your code, remember to always use tuples at the right of the % operator, or even better use the .format() method.

Upvotes: 1

user 12321
user 12321

Reputation: 2906

Are you sure the self model you send is the right one?

This ValidationError is thrown when you have declare a ReferenceField in a document, and you try to save this document before saving the referenced document (Mongoengine represents a reference field in MongoDB as an dictionnay containing the class and the ObjectId of the reference).

Upvotes: 0

Related Questions