#29173: Models with custom fields returns the given value instead of stored
value
-------------------------------------+-------------------------------------
Reporter: Xtreak | Owner: nobody
Type: Bug | Status: new
Component: Database | Version: 2.0
layer (models, ORM) |
Severity: Normal | Keywords:
Triage Stage: | Has patch: 0
Unreviewed |
Needs documentation: 0 | Needs tests: 0
Patch needs improvement: 0 | Easy pickings: 0
UI/UX: 0 |
-------------------------------------+-------------------------------------
When there is a custom field in the model and we do some transformation
before storing it to the database. Hence while creating the object we give
a value which is transformed and stored. But the returned object as a
result of the create call has the given value instead of the transformed
value.
In the below model I have a custom field FooField which always returns
"foo" as the value to be stored but when I create an object with another
value say 'a' it only has the value 'a' stored in the returned object. I
need to do a refresh_from_db to clear the wrong value and to fetch the
correct value. I couldn't find this documented at
[https://docs.djangoproject.com/en/2.0/howto/custom-model-fields/]. If
this an expected behavior adding a note in the documentation will be of
help.
models.py
{{{
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class FooField(models.CharField):
def to_python(self, value):
value = super(self.__class__, self).to_python(value)
return "foo"
def get_prep_value(self, value):
value = super(self.__class__, self).get_prep_value(value)
return "foo"
class FooBase(models.Model):
base_field = models.CharField(max_length=120)
class Foo(FooBase):
custom_field = FooField(max_length=120)
}}}
Shell session
{{{
In [11]: bar = Foo.objects.create(base_field='1', custom_field='a')
In [12]: bar.custom_field
Out[12]: 'a'
In [13]: bar.refresh_from_db()
In [14]: bar.custom_field
Out[14]: 'foo'
In [15]: bar.id
Out[15]: 10
}}}
{{{
sqlite> select * from TestApp_foo;
10|foo
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/29173>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/052.43064838352978e46b651b8459a8c8a7%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.