简体   繁体   中英

How do I create a unique property in python on google app engine?

In some database technologies, for a attribute in a record, you can guarantee uniqueness of that attribute within the entire database. An example of this might be a email_address attribute in a User record. By setting email_address to unique, you guarantee that a particular email address can only appear in one record in the entire database.

Is there any way in google app engine to have unique properties for a given model? As a example, could I have a User(db.Model) entity with a email property that is guaranteed unique across the entire datastore?

I found this resource here , which might prove helpful.

The only help you get from GAE's datastore regarding "uniqueness" is via entities' keys -- but then, I see the URL you quote also noticed that and shows one way to exploit this fact. To get anywhere beyond keys, you need to perform your checks at application level (before you put an entity, or a change to a unique set of properties, you make a suitable query [[key-only for speed]] and check that it comes up empty), but that gets pretty costly (and hard to make transaction-safe).

我使用record.key()。id() 博客如何, 尼克·约翰逊的博客提供了专家建议

I have implemented it in the following way by overriding the put method and using the key.name

class Program(db.Model):
    name = db.StringProperty("Title")
    slug = db.StringProperty("Slug")
    def put(self):
        if Program.get_by_key_name(self.slug):
            raise UniqueConstraintViolation("slug", self.slug)
        self._key_name = self.slug
        return db.Model.put(self)


class UniqueConstraintViolation(Exception):
    def __init__(self, scope, value):
        super(UniqueConstraintViolation, self).__init__("Value '%s' is not unique within scope '%s'." % (value, scope, ))

I save the slug as key.name and if you try to add another program it will check if the key name already exist. It's probably not a nice way, im also a beginner at python / app engine.

This is good article about somebody using a helper model: http://squeeville.com/2009/01/30/add-a-unique-constraint-to-google-app-engine/

Edit: I saw you also provided that article lol.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM