How to use ndb key with integer_id?

泪湿孤枕 提交于 2019-12-11 00:09:48

问题


I see the document https://developers.google.com/appengine/docs/python/ndb/keyclass#Key_integer_id

Returns the integer id in the last (kind, id) pair, or None if the key has an string id or is incomplete.

see I think the id of a key can be a int ; so I write

    r = ndb.Key(UserSession, int(id)).get()
    if r:
        return r.session

but the dev_server.py , will always raise

  File "/home/bitcoin/down/google_appengine/google/appengine/datastore/datastore_stub_util.py", line 346, in CheckReference
    raise datastore_errors.BadRequestError('missing key id/name')
BadRequestError: missing key id/name

I chanage the int(id) -> str(id)

seems right ;

so my question is , How to use ndb key with integer_id ?

the model is

class UserSession(ndb.Model):
    session = ndb.BlobProperty()

回答1:


The type of the id you use when reading the entity must match the type of the id you used when you wrote the entity. Normally, integer ids are assigned automatically when you write a new entity without specifying an id or key; you then get the id out of the key returned by entity.put(). It is generally not recommended to assign your own integer ids; when the app assigns the keys, the convention is that they should be strings.




回答2:


There's an easier way to fetch:

UserSession.get_by_id(int(id))

https://developers.google.com/appengine/docs/python/ndb/modelclass#Model_get_by_id

If that doesn't work, I suspect that id is wrong or empty.




回答3:


There must be something wrong with your variable 'id'.

Your code here should be no problem, and it's better to user long instead of int.

You can try your code on interactive console of development server with specific integer id.




回答4:


It may be easier to identify your entities in the sessions with their keys instead of their ids. There really is no need to extract the ID from the key to identify the session (other than maybe saving a bit of memory. I think the way your thinking is based on a RDB. I learned that using the key actually makes entity/session identifications easier.




回答5:


'id' is also a python builtin function. Maybe you are taking that by mistake.



来源:https://stackoverflow.com/questions/15187813/how-to-use-ndb-key-with-integer-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!