xjq233p_1
xjq233p_1

Reputation: 8060

How do I attach temporary information to my appengine ndb model instance?

I am trying to set an attribute to my model,

class Foo(ndb.Model):
  name = ndb.StringProperty()
  1. Retrieve Foo object from memcache
  2. If not in memcache, query from database. Here I would like to attach additional information to the Foo instance foo.special_name = "don't persist this"
  3. Pass this object from memcache to my custom JsonEncoder
  4. Dump this object to a dictionary, foo = {name:"hello", special_name:"don't persist this"}

AFAIK, I can't set attributes of ndb.Model classes that are not fields.

I am afraid to use ndb.Expando because I am worried that this object will get persisted and special_name will be saved to my database.

What's the cleanest way to add temporary disposable value to foo?

EDIT:

>>> class Foo(ndb.Model):
  name = ndb.StringProperty()
>>> f = Foo()
>>> f.put()
Key('Foo', 26740114379063)
>>> f.bar = 123 
>>> f
Foo(name=None)
>>> f.bar
Traceback (most recent call last):
  File "/base/data/home/apps/shell/1.335852500710379686/shell.py", line 267, in get
    exec compiled in statement_module.__dict__
  File "<string>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'bar'
>>> setattr(f, 'bar', 123)
>>> f
Foo(name=None)
>>> f.bar
Traceback (most recent call last):
  File "/base/data/home/apps/shell/1.335852500710379686/shell.py", line 267, in get
    exec compiled in statement_module.__dict__
  File "<string>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'bar'
>>> setattr(f, 'bar', 123)
>>> getattr(f, 'bar')
Traceback (most recent call last):
  File "/base/data/home/apps/shell/1.335852500710379686/shell.py", line 267, in get
    exec compiled in statement_module.__dict__
  File "<string>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'bar'

Upvotes: 1

Views: 168

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

"I can't set attributes of ndb.Model classes that are not fields."

Why would you think this? Model instances are just objects, and like any other object in Python [*], you can set arbitrary attributes on them as much as you like.

[*]: (as long as the class doesn't define __slots__, which ndb.Model doesn't)

Upvotes: 2

Related Questions