How to use ndb key with integer_id?

2019-07-24 19:07发布

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

5条回答
等我变得足够好
2楼-- · 2019-07-24 19:27

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.

查看更多
甜甜的少女心
3楼-- · 2019-07-24 19:29

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.

查看更多
淡お忘
4楼-- · 2019-07-24 19:33

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

查看更多
【Aperson】
5楼-- · 2019-07-24 19:34

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.

查看更多
仙女界的扛把子
6楼-- · 2019-07-24 19:35

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.

查看更多
登录 后发表回答