i'm trying implement custom django field keep in db name of 1 of model classes (e. g. "cat", "dog", "restaurant", "superprivatecommercialdatapiece", etc.) , return class object when requested:
class cat(models.model): ... class somedatapiece(models.model): relatedto = mygloriousfieldtype(null=true) ... newpiece = somedatapiece() newpiece.relatedto = cat print newpiece.relatedto # should print <class 'myproj.myapp.models.cat'> and i've made this. i've subclassed models.field, set __metaclass__, etc.:
class mygloriousfieldtype(models.field): description = "no description, gloriosity." __metaclass__ = models.subfieldbase def __init__(self, *args, **kwargs): kwargs['max_length'] = 40 super(blocktypefield, self).__init__(*args, **kwargs) def db_type(self, connection): return 'char(40)' def to_python(self, value): if not value: return none elif inspect.isclass(value) , issubclass(value, models.model): return value elif hasattr(myproj.myapp.models, value): return getattr(myproj.myapp.models, value) else: raise validationerror("invalid model name string") def get_db_prep_value(self, value, **kwargs): if inspect.isclass(value) , issubclass(value, models.model): return value.__name__ else: # never raised raise validationerror("invalid value, model subclass expected") def value_to_string(self, instance): value = self._get_val_from_obj(obj) return self.get_prep_value(value) and in code above works expected. i've registered of models containing such fields in admin, , can create such objects; text input created mygloriousfieldtype fields.
the crisis begins when try edit existing object mygloriousfieldtype field. first, fills text field "cat object" instead of "cat". second, when change "cat" , click "save changes" gives error:
typeerror @ /admin/myapp/somedatapiece/3/ unbound method prepare_database_save() must called cat instance first argument (got mygloriousfieldtype instance instead) so, doing wrong?
well, i've figured out. problem inside django core. fields can't return python objects containing models.field attributes prepare_database_save, otherwise error occures. hack solve return tuple (myclassobject, ) instead of myclassobject in to_python(). odd, can do... maybe i'll try post issue somewhere on django's github page.
Comments
Post a Comment