开发者

Django model data consistency

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜