Django Virtual Field: set property value from virtual field

I am trying to understand the django ModelFields internals to implement the new django-hstore function .

Basically, I want to create virtual fields from the HStore Dictionary, which has a predefined schema.

As a first step, I would like to hide the field of the real HStore dictionary and instead use the value present in the virtual fields to compile the final HStore dictionary.

I was able to get the administrator to work correctly for all actions except the save action, which does not save the value of the virtual field in the HStore dictionary.

Here is my actual VirtualField 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)

models.py (prototyping only)

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()

I thought save_form_data strong> would do the trick, but that is not the case.

django docs "The subfieldBase metaclass" " ", , .

?

- ?

, "" "" hstore ? , , .

...

+4

Source: https://habr.com/ru/post/1545410/


All Articles