django - Ndb models: assure uniqueness in datastore using custom key_name -
i'm trying mimic django's unique_together
feature, can't seem straight
class myclass(ndb.model): name = 'name' surname = 'surname' phone = 'phone' def get_unique_key(self): return self.name + "|" + self.surname + "|" + self.phone
"yeah, pretty easy" not
according accepted answer in this post, assigning id
param in obj constructor enough. don't want handle in view. ideally, i'd this:
object = myclass() object = object.custom_populating_method(form.cleaned_data) object.id = object.get_unique_key() object.put()
or better, place in _pre_put_hook
, id
set last thing before saving (and maybe checking enforcing uniqueness of data across datastore).
apparently, wrong. way achieve hacking view:
unique_id = "|" + form.cleaned_data['bla'] + "|" + form.cleaned_data ... object = myclass(id=unique_id)
which awful , wrong (since every change model's requirements needs inspected in views). plus, i'd end doing couple of ugly calls fetch related data. i've spent time, probably, on problem see exit , hope i'm missing obvious here, can't find example nor proper documentation around subject. has hint or experience similar?
tl;dr: there nice way achieve without adding unnecessary code views?
(i'm "using" django , ndb's models on datastore)
thanks
use factory or class method construct instance.
class myclass(ndb.model): name = ndb.stringproperty() surname = ndb.stringproperty() phone = ndb.stringproperty() @staticmethod def get_unique_key(name,surname,phone): return '|'.join((name,surname,phone)) @classmethod @transactional def create_entity(cls,keyname,name,surname,phone): key = ndb.key(cls, cls.get_uniquekey()) ent = key.get() if ent: raise someduplicateerror() else: ent = cls(key=key, name=name,surname=surname,phone=phone) ent.put()
newobj = myclass.create_entity(somename, somesurname, somephone)
doing way allows ensure key unique creatin key , tring fetch first.
Comments
Post a Comment