﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
7974	cannot replace custom fields without using database format	mspang	nobody	"If you use to_python() to build a Python class for a custom field (as explained in the tutorial), you lose the ability to directly assign to that field. Example:[[br]][[br]]
Model:
{{{
class Int(object):
  def __init__(self, value):
    self.int_value = value

class IntField(models.Field):
  __metaclass__ = models.SubfieldBase

  def get_default(self):
    return 0

  def to_python(self, value):
    return Int(int(value))

  def get_db_prep_save(self, value):
    return value.int_value

  def db_type():
    return 'int'

class IntModel(models.Model):
  int_field = IntField()
}}}

Code:
{{{
>>> a = models.IntModel()
>>> a.int_field
<testproj.testapp.models.Int object at 0xf696cf8c>
>>> a.int_field.int_value
0
>>> a.int_field.int_value = 10
>>> a.int_field.int_value
10
>>> a.int_field = models.Int(30)
Traceback (most recent call last):
  File ""<console>"", line 1, in ?
  File ""/opt/django/db/models/fields/subclassing.py"", line 34, in __set__
    obj.__dict__[self.field.name] = self.field.to_python(value)
  File ""/home/mspang/testproj/testapp/models.py"", line 97, in to_python
    return Int(int(value))
TypeError: int() argument must be a string or a number
}}}

We can never assign to int_field directly using its python type. This is especially crippling if the object itself is immutable, since in that case you have to serialize and deserialize the field once per change. To solve this, to_python() must not be called during assignment, only during database loads. Introducing a new method ('get_db_prep_load') for this purpose seems appropriate."		closed	Database layer (models, ORM)	1.0-alpha		wontfix		Jacob	Unreviewed	0	0	0	0	0	0
