2

I have a model class which looks like this

class Test(database.Model):
       created_date = database.Column(database.DateTime,
                                      default=datetime.utcnow,
                                      nullable=False)

I'm getting this via running command

all = Test.query.all()

Now, this gets me dates in format 2017-09-05 09:45:28 I want to get ISO representation of dates like 2017-09-05T09:45:28.263000.

One option is to post-process the data I received, but what is the better approach? Is there any SQLAlchemy construct which will help me achieve this?

Ganesh Satpute
  • 3,664
  • 6
  • 41
  • 78

1 Answers1

8

Let's clarify something, because your question might be a little bit misleading.

Test.query.all() returns list of Test objects, where each is representation of the Model that you've defined and should contain declared attributes (like creation_date).

>>> t = Test.query.all()
>>> t
[<Test object at 0x10010d2d0>, ...]

Now - creation date attribute is a datetime object and doesn't give you any specific representation per se. Instead, it contain some methods (like __str__, __repr__, isoformat, etc.) that helps you get desired representation of datetime object.

>>> t[0].created_date
datetime.datetime(2017, 3, 2, 15, 34, 10, 272)
>>> t[0].created_date.isoformat()
'2017-03-02T15:34:10.000272'

The way how you present the data it's not something that SQLAlchemy layer should be aware of, as SQLAlchemy is ORM (model layer) and by design shouldn't lay in controller/view layer: more on mvc

If you really want have some predefined representation of some attribute in SQLAlchemy Models, use @property decorator in your Test class.

@property
def created_date(self):
    return self.created_date.isoformat()

More on that in SQLAlchemy documentation: docs

erhesto
  • 1,176
  • 7
  • 20
  • Your points are correct! I was indeed missing the part that the serialization is taken care of `marshmallow` library. I've raised another question for customizing serialization https://stackoverflow.com/questions/46074589/python-marshmallow-customize-formatting-of-class-member – Ganesh Satpute Sep 06 '17 at 11:59