Skip to content
This repository has been archived by the owner on Feb 21, 2020. It is now read-only.

Commit

Permalink
Use Field.get_prep_value for model field values
Browse files Browse the repository at this point in the history
The motivation for this is to ensure the value is not a complex
object, but rather a representation of a primitive value.

Thanks to @hauru for the discussion.

Signed-off-by: Byron Ruth <b@devel.io>
  • Loading branch information
bruth committed Feb 24, 2016
1 parent fadfc15 commit 29f96b2
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions preserialize/utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import collections
from django.db import models
from django.db.models.fields import Field
from django.db.models import FieldDoesNotExist


PSEUDO_SELECTORS = (':all', ':pk', ':local', ':related')
Expand Down Expand Up @@ -115,8 +118,21 @@ def get_field_value(obj, name, allow_missing=False):

if hasattr(obj, name):
value = getattr(obj, name)

# Check if the name of is field on the model and get the prep
# value if it is a Field instance.
if isinstance(obj, models.Model):
try:
field = obj._meta.get_field(name)

if isinstance(field, Field):
value = field.get_prep_value(value)
except FieldDoesNotExist:
pass

elif hasattr(obj, '__getitem__') and name in obj:
value = obj[name]

elif not allow_missing:
raise ValueError('{} has no attribute {}'.format(obj, name))

Expand Down

0 comments on commit 29f96b2

Please sign in to comment.