forked from ietf-tools/datatracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserialize.py
More file actions
25 lines (19 loc) · 685 Bytes
/
serialize.py
File metadata and controls
25 lines (19 loc) · 685 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import datetime
from django.db import models
def object_as_shallow_dict(obj):
"""Turn a Django model object into a dict suitable for passing to
create and for serializing to JSON."""
d = {}
for f in obj._meta.fields:
n = f.name
if isinstance(f, models.ForeignKey):
n = f.name + "_id"
v = getattr(obj, n)
if isinstance(f, models.ManyToManyField):
v = list(v.values_list("pk", flat=True))
elif isinstance(f, models.DateTimeField):
v = v.astimezone(datetime.UTC).isoformat()
elif isinstance(f, models.DateField):
v = v.strftime('%Y-%m-%d')
d[n] = v
return d