Skip to content

Commit d2243ba

Browse files
committed
Added a utility function to convert objects to dictionaries (for comparison, for instance)
- Legacy-Id: 17468
1 parent bd89c7f commit d2243ba

1 file changed

Lines changed: 17 additions & 1 deletion

File tree

ietf/utils/models.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
# Copyright The IETF Trust 2015, All Rights Reserved
1+
# Copyright The IETF Trust 2015-2020, All Rights Reserved
2+
3+
import itertools
24

35
from django.db import models
46

@@ -26,3 +28,17 @@ class OneToOneField(models.OneToOneField):
2628
def __init__(self, to, on_delete=models.CASCADE, **kwargs):
2729
return super(OneToOneField, self).__init__(to, on_delete=on_delete, **kwargs)
2830

31+
def object_to_dict(instance):
32+
"""
33+
Similar to django.forms.models.model_to_dict() but more comprehensive.
34+
35+
Taken from https://stackoverflow.com/questions/21925671/#answer-29088221
36+
with a minor tweak: .id --> .pk
37+
"""
38+
opts = instance._meta
39+
data = {}
40+
for f in itertools.chain(opts.concrete_fields, opts.private_fields):
41+
data[f.name] = f.value_from_object(instance)
42+
for f in opts.many_to_many:
43+
data[f.name] = [i.pk for i in f.value_from_object(instance)]
44+
return data

0 commit comments

Comments
 (0)