python - Django Virtual Field: set value of a property from a virtual field -
i'm trying understand internals of django modelfields implement new feature on django-hstore.
basically want create virtual fields hstore dictionary has predefined schema.
as first step, i'd hide actual hstore dictionary field , utilize instead value nowadays in virtual fields compose final hstore dictionary.
i've been able create admin work actions except save action, not save value of virtual field hstore dictionary.
here's actual virtualfield code:
# virtual.py 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 value of field in given model instance. """ hstore_field = getattr(obj, self.hstore_field_name) homecoming hstore_field[self.attname] def save_form_data(self, instance, data): hstore_field = getattr(instance, self.hstore_field_name) hstore_field[self.attname] = info setattr(instance, self.hstore_field_name, hstore_field)
models.py (just prototyping)
class modeleddatabag(models.model): name = models.charfield(max_length=32) info = hstore.modeleddictionaryfield(schema={ 'number': { 'type': int, 'default': 0 } }) number = virtualfield(hstore_field_name='data') objects = hstore.hstoremanager()
i thought save_form_data trick that's not true.
in django docs i've found "the subfieldbase metaclass" section in "custom model fields" page looks need.
is right path follow?
is there illustration study?
anyone can provide illustration of how set value of key "number" of hstore field "data" , store in database? there think know how go ahead.
thanks...
the right reply utilize python descriptors, implemented solution here:
https://github.com/djangonauts/django-hstore/blob/8229e850e1631d8fd038436d2aa1fccb26b9a699/django_hstore/virtual.py#l29
this feature developed open source project called nodeshot, here's illustration implementation schema taken settings.py:
https://github.com/ninuxorg/nodeshot/blob/028bb28009bf73b2a4fc087f811e1b66c958907e/nodeshot/core/nodes/models/node.py#l49
python django django-models
No comments:
Post a Comment