title: Django Virtual Field: set value of a property from a virtual field
body: <p>I'm trying to understand the internals of django ModelFields to implement a new feature on <a href="https://github.com/djangonauts/django-hstore" rel="noreferrer">django-hstore</a>.</p>
  
  <p>Basically I want to create virtual fields from an HStore Dictionary which has a predefined schema.</p>
  
  <p>As a first step, I'd like hide the actual HStore Dictionary field and use instead the value present in the virtual fields to compose the final HStore Dictionary.</p>
  
  <p>I've been able to make the admin work properly for all actions except for the save action, which does not save the value of the virtual field into the HStore dictionary.</p>
  
  <p>Here's my actual VirtualField code:</p>
  
  <pre><code># virtual.py
  from django.db.models.fields import Field
  
  
  class VirtualField(Field):
      """ Virtual Field """
  
      def __init__(self, *args, **kwargs):
          try:
              self.hstore_field_name = kwargs.pop('hstore_field_name')
          except KeyError:
              raise ValueError('missing hstore_field_name keyword argument')
          super(VirtualField, self).__init__(*args, **kwargs)
  
      def contribute_to_class(self, cls, name, virtual_only=True):
          super(VirtualField, self).contribute_to_class(cls, name, virtual_only)
  
      def value_from_object(self, obj):
          """
          Returns the value of this field in the given model instance.
          """
          hstore_field = getattr(obj, self.hstore_field_name)
          return hstore_field[self.attname]
  
      def save_form_data(self, instance, data):
          hstore_field = getattr(instance, self.hstore_field_name)
          hstore_field[self.attname] = data
          setattr(instance, self.hstore_field_name, hstore_field)
  </code></pre>
  
  <p>models.py (just prototyping)</p>
  
  <pre><code>class ModeledDataBag(models.Model):
      name = models.CharField(max_length=32)
      data = hstore.ModeledDictionaryField(schema={
          'number': {
              'type': int,
              'default': 0
          }
      })
  
      number = VirtualField(hstore_field_name='data')
  
      objects = hstore.HStoreManager()
  </code></pre>
  
  <p>I thought <strong>save_form_data</strong> would do the trick but that's not true.</p>
  
  <p>In the django docs i've found <a href="https://docs.djangoproject.com/en/1.6/howto/custom-model-fields/#the-subfieldbase-metaclass" rel="noreferrer">"The SubfieldBase metaclass"</a> section in the "Custom Model Fields" page which looks like what I need.</p>
  
  <p>Is it that the right path to follow?</p>
  
  <p>Is there any example to study?</p>
  
  <p>Anyone can provide an example of how to set the value of the key "number" of the hstore field "data" and store it in the database?
  From there I think I know how to go ahead.</p>
  
  <p>Thanks...</p>