Unique field in pimongo

What is the easiest way to avoid field collisions working with pymongo? I have a very simple structure for the Location class (name, pool, description and geolocation), and I would like to make sure duplicate names are not allowed. Do I use flask and pymongo?

I tried to do this:

from flask import Flask from flask.ext.pymongo import PyMongo app = Flask(__name__) mongo = PyMongo(app) mongo.db.court.ensureIndex( { "name": 1, "slug": 1 } ) 

but this gives me an error: RuntimeError: works out of context of the application.

+4
source share
2 answers

use unique indexes and you will not have two documents that have the same field value. this does not have to be a flag, but rather it is specific to mongodb.

if you're lazy or indexes give you a headache, just use the _id field as the location name. in this case, you must make sure that your documents are not overwritten.

+4
source

The best place to call your ensure_index calls is somewhere before you call run() in your flash application. You want to make sure that your indexes are installed before you try to service any requests, because creating an index while the site is running will be very irrelevant. The error you get is related to the fact that you need the application context. Try:

 app = Flask(__name__) mongo = PyMongo(app) if __name__ == '__main__': with app.app_context(): mongo.db.court.ensure_index( [("name", ASCENDING), ("slug", ASCENDING)], unique=True ) app.run() 

As @thkang said, you should use a unique index to ensure that two documents do not have the same value for a field or set of fields taken together. Learn more about this and the pymongo ensure_index syntax in pymongo docs .

+4
source

Source: https://habr.com/ru/post/1502681/


All Articles