本文介绍了返回Django模型上的空字段的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个模型,其中一个字段通常是空白字符串.有没有办法返回(例如)字符串"default"而不是该模型查询的空白字符串?
I have a model in which one field is often the blank string. Is there a way to return (for e.g.) the string 'default' instead of that blank string for queries on that model?
class MyModel(models.Model):
...
afield = models.CharField(...) # many rows set afield to ''
我执行查询时
o = MyModel.objects.all()
vars(o[0])
{...
'afield': '' # afield is empty
...}
我宁愿
vars(o[0])
{...
'afield': 'default'
...}
有没有办法做到这一点?有没有比在模型内部更好的方法呢?
Is there a way to do this? Is there a better way to implement this than inside the model?
注意:
- 我不想存储字符串'default'
- 此答案更改了数据库,我想避免这种情况
- I do not want to store the string 'default'
- this answer alters the database, I want to avoid that
推荐答案
在视图中将其作为逻辑的一部分来处理可能更好,很多,很多,但是您可以使用属性和设置器来做到这一点:
It is probably much, much, much better to handle this in views as part of your logic, but you could use properties and setters to do this:
class MyModel(models.Model):
_afield = models.CharField(...)
@property
def afield(self):
if self._afield:
return self._afield
else:
return "default"
@afield.setter
def afield_setter(self,value):
self._afield = value
这篇关于返回Django模型上的空字段的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!