开发者

Django model data consistency

开发者 https://www.devze.com 2023-02-07 20:15 出处:网络
When creating a form, you can define a bunch of methods, clean_xyz, to make sure the data gets forced into the correct format. Is there any way to do this on 开发者_如何学Goa model level?

When creating a form, you can define a bunch of methods, clean_xyz, to make sure the data gets forced into the correct format. Is there any way to do this on 开发者_如何学Goa model level?

Perhaps I can override the field setters somehow? I want it so that if I write something like

my_address.postal_code = 'a1b2c3'

It will automatically get formatted into A1B 2C3. Perhaps throw an exception if it can't be converted. That way I know I'll never have any malformed data in the database.


As of Django 1.2 there's a section in the docs that deal with the validation of models, I suggest you look at Model.clean().


Maybe overriding save() on your model might help you out?

def save(self, *args, **kwargs):
    # do your formatting
    self.postal_code = somefancyformattingmethod()
    # save it to the database
    super(YourModel, self).save(*args, **kwargs)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号