do properties work on django model fields?

前端 未结 4 704
既然无缘
既然无缘 2020-11-29 22:21

I think the best way to ask this question is with some code... can I do this? (edit: ANSWER: no)

class MyModel(models.Model):    
    foo =          


        
4条回答
  •  感动是毒
    2020-11-29 22:51

    The previous solutions suffer because @property causes problems in admin, and .filter(_foo).

    A better solution would be to override setattr except that this can cause problems initializing the ORM object from the DB. However, there is a trick to get around this, and it's universal.

    class MyModel(models.Model):
        foo = models.CharField(max_length = 20)
        bar = models.CharField(max_length = 20)
    
        def __setattr__(self, attrname, val):
            setter_func = 'setter_' + attrname
            if attrname in self.__dict__ and callable(getattr(self, setter_func, None)):
                super(MyModel, self).__setattr__(attrname, getattr(self, setter_func)(val))
            else:
                super(MyModel, self).__setattr__(attrname, val)
    
        def setter_foo(self, val):
            return val.upper()
    

    The secret is 'attrname in self.__dict__'. When the model initializes either from new or hydrated from the __dict__!

提交回复
热议问题