给定一个模型
class Template(models.Model):
colour = models.CharField(default="red", blank = True, null=True)
我如何安排它以便对颜色的任何访问都返回存储在该字段中的值,或者如果该字段为空/空则返回红色?
default=red首次创建时会将“红色”放入字段中,但如果随后将其编辑为空白,我希望访问它以返回“红色”,而不是“”
更新:我尝试了下面建议的属性解决方案,但我正在使用 JSON 序列化来实现 REST API 并且属性(例如 colour
)不会被序列化,并且序列化 _colour
破坏 API
最佳答案
您可以改为创建一个单独的方法:
def get_colour(self):
if not self.colour:
return 'red'
else:
return self.colour
另一种方法是使用属性。
http://www.djangoproject.com/documentation/models/properties/
关于python - 如果设置为 null,如何创建具有默认值的 Django 模型字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2156585/