1

In my flask sqlalchemy based app, I have a model like this:

class Foo(object):
    start_date = db.Column(db.DateTime())

It works fine but when I use the template engine to print out the date onto HTML page by doing {{ foo.start_date }}, it'll print a ugly line like 2015-8-8 00:00:00. Trying to come up with my own format, I thought of something clever (at least before I hit the problem)

class Foo(object):
    start_date = db.Column(db.DateTime())
    def __getattr__(self, name):
         return "{0}-{1}-{2}".format(self.start_date.year....)

However, something internal of SQLAlchemy doesn't like this. When a new object is created, it'll raise the following exception:

  File "<string>", line 6, in __init__
  File "/home/wenliang/work/template/flask/local/lib/python2.7/site-packages/sqlalchemy/ext/declarative/base.py", line 526, in _declarative_constructor
    setattr(self, k, kwargs[k])
  File "/home/wenliang/work/template/flask/local/lib/python2.7/site-packages/sqlalchemy/orm/attributes.py", line 226, in __set__
    instance_dict(instance), value, None)
  File "/home/wenliang/work/template/flask/local/lib/python2.7/site-packages/sqlalchemy/orm/attributes.py", line 694, in set
    state._modified_event(dict_, self, old)
AttributeError: 'NoneType' object has no attribute '_modified_event'

Any one seen this before?

lang2
  • 11,433
  • 18
  • 83
  • 133

1 Answers1

3

SQLAlchemy uses __getattr__ internally. If you overload it, the whole alchemy magic will not work anymore.

The field you are accessing is a DateTime object. If you want to format that into a string in any other way as the default rendering, you should use strftime().

https://stackoverflow.com/a/4830620/3929826 gives an example. https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior has the documenatation on the format string.

Community
  • 1
  • 1
Klaus D.
  • 13,874
  • 5
  • 41
  • 48