I need some properties to be unique. How can I achieve this?
Is there something like unique=True?
I’m using Google App Engine for Python.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There’s no built-in constraint for making sure a value is unique. You can do this however:
I use
keys_only=Truebecause it’ll improve the performance slightly by not fetching the data for the entity.A more efficient method would be to use a separate model with no fields whose key name is made up of property name + value. Then you could use
get_by_key_nameto fetch one or more of these composite key names and if you get one or more not-Nonevalues, you know there are duplicate values (and checking which values were notNone, you’ll know which ones were not unique.)As onebyone mentioned in the comments, these approaches – by their get first, put later nature – run the risk concurrency issues. Theoretically, an entity could be created just after the check for an existing value, and then the code after the check will still execute, leading to duplicate values. To prevent this, you will have to use transactions: Transactions – Google App Engine
If you’re looking to check for uniqueness across all entities with transactions, you’d have to put all of them in the same group using the first method, which would be very inefficient. For transactions, use the second method like this:
UniqueConstraint.check(...)will assume that every single key/value pair must be unique to return success. The transaction will use a single entity group for every model kind. This way, the transaction is reliable for several different fields at once (for only one field, this would be much simpler.) Also, even if you’ve got fields with the same name in one or more models, they will not conflict with each other.