Annotate multiple values as JSONObject - parse datetime
I'm annotating my QuerySet as follows, using JSONObject
, to obtain multiple fields from Scan
:
MyModel.objects.annotate(
myscan=Subquery(
Scan.objects
.all()
.values(data=JSONObject(
id='id',
nin='nin',
datetime='datetime')
)[:1]
)
)
I want to get a proper datetime representation though, somehow.
When I try to use myscan.datetime
, I get the string representation (e.g. datetime': '2024-12-31T09:19:30.221953+00:00
.
How can I either return the datetime object itself (instead of a string; assuming this is impossible when using JSONObject
) or alternatively do a strptime()
before returning the string as part of the JSON?
Obviously I could parse the string, convert to datetime and then do strptime()
again, but that seems like a dirty solution. Any suggestions?
When using PostgreSQL, the datetime format can be parsed/casted as follows (using the Postgres format):
from django.db.models.functions import Cast
from django.db.models import Subquery, F, Value, Func, CharField
MyModel.objects.annotate(
myscan=Subquery(
Scan.objects
.all()
.values(data=JSONObject(
id='id',
nin='nin',
datetime=Cast(
Func(
F('datetime'),
Value('DD-MM-YYYY HH24:MI'),
function='TO_CHAR'
),
output_field=CharField()
)
)
)[:1]
)
)