views:

214

answers:

3

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.

+2  A: 

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).

Alex Martelli
+1  A: 

I use record.key().id() blogged how, Nick Johnson's blog has pro expert advice

LarsOn
A: 

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.

Sam S