在创建表单时,可以定义一组方法clean_xyz,以确保数据被强制转换为正确的格式。有没有办法在模型级别上做到这一点?
也许我可以以某种方式覆盖字段设置器?我想要它,这样如果我写了像这样的东西
my_address.postal_code = 'a1b2c3'它会自动被格式化成A1B 2C3。如果它不能被转换,可能抛出一个异常。这样,我就知道数据库中永远不会有任何格式错误的数据。
发布于 2011-01-31 15:20:27
从Django1.2开始有a section in the docs that deal with the validation of models,我建议你看看Model.clean()。
发布于 2011-01-31 15:10:47
也许覆盖模型上的save()可能会对您有所帮助?
def save(self, *args, **kwargs):
# do your formatting
self.postal_code = somefancyformattingmethod()
# save it to the database
super(YourModel, self).save(*args, **kwargs)https://stackoverflow.com/questions/4847951
复制相似问题