Added a utility function to convert objects to dictionaries (for comparison, for instance)
- Legacy-Id: 17468
This commit is contained in:
parent
bd89c7f5be
commit
d2243ba93d
|
@ -1,4 +1,6 @@
|
||||||
# Copyright The IETF Trust 2015, All Rights Reserved
|
# Copyright The IETF Trust 2015-2020, All Rights Reserved
|
||||||
|
|
||||||
|
import itertools
|
||||||
|
|
||||||
from django.db import models
|
from django.db import models
|
||||||
|
|
||||||
|
@ -26,3 +28,17 @@ class OneToOneField(models.OneToOneField):
|
||||||
def __init__(self, to, on_delete=models.CASCADE, **kwargs):
|
def __init__(self, to, on_delete=models.CASCADE, **kwargs):
|
||||||
return super(OneToOneField, self).__init__(to, on_delete=on_delete, **kwargs)
|
return super(OneToOneField, self).__init__(to, on_delete=on_delete, **kwargs)
|
||||||
|
|
||||||
|
def object_to_dict(instance):
|
||||||
|
"""
|
||||||
|
Similar to django.forms.models.model_to_dict() but more comprehensive.
|
||||||
|
|
||||||
|
Taken from https://stackoverflow.com/questions/21925671/#answer-29088221
|
||||||
|
with a minor tweak: .id --> .pk
|
||||||
|
"""
|
||||||
|
opts = instance._meta
|
||||||
|
data = {}
|
||||||
|
for f in itertools.chain(opts.concrete_fields, opts.private_fields):
|
||||||
|
data[f.name] = f.value_from_object(instance)
|
||||||
|
for f in opts.many_to_many:
|
||||||
|
data[f.name] = [i.pk for i in f.value_from_object(instance)]
|
||||||
|
return data
|
||||||
|
|
Loading…
Reference in a new issue