Utkarsh
Utkarsh

Reputation: 41

Adding custom id field in flask/mongoengine document

I am working on revamping an application from Django/MySQL to flask/mongo-engine & am having trouble creating a model with an id field. This is a sample model:

class Location(db.Document):
    id = db.IntField(unique=True)
    name = db.StringField(max_length=200, required=True)
    # other fields in the document ...

For backward compatibility, I require the field id named as is. This used to work fine in MySQL but mongo-engine gives the ValidationError -- Field is required: ['id'] Invalid Object ID: ['auto_id_0'] for documents of the above model.

I also tried using the db_field parameter as in

id = db.IntField(db_field='l_id', unique=True)

...but to no avail.

Do note that I have no intentions of overriding the default ObjectID field of mongodb. Is there any workaround for this, other than renaming the field upon deserialization?

Upvotes: 1

Views: 5152

Answers (2)

vboreda514
vboreda514

Reputation: 350

This worked for me:

class Location(db.Document):
    _id = db.ObjectIdField()
    id = db.IntField(unique=True)
    name = db.StringField(max_length=200, required=True)
    # other fields in the document ...

This caused the id IntField() to correctly grab the id field from Mongo.

Upvotes: 0

Nikita Kotlov
Nikita Kotlov

Reputation: 29

Try

class Location(db.Document):
    myid = db.IntField(db_field='id', unique=True)
    name = db.StringField(max_length=200, required=True)
    # other fields in the document ...

And operate with it as if the field is named myid.

Location.objects.create(myid=real_id)
Location.objects.filter(myid=real_id)

Upvotes: 0

Related Questions