Django模型字段,替代值返回如果为null? [英] Django model field, alternative value return if null?
本文介绍了Django模型字段,替代值返回如果为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果该字段具有空值,是否有方法为django模型字段返回不同的设置值?
Is there a way to return a different set value for a django model field if that field has a null value?
我拥有个人资料图片(image_url)的用户,对于没有人的用户,我想要返回默认的无头像网址,而不是无。
I have users with profile images (image_url), for users who do not have one I'd like to return a default no avatar url, rather than 'None'.
class User(models.Model):
name = models.CharField(max_length=800)
image_url = models.URLField(max_length=2000, blank=True, null=True)
推荐答案
最简单的方法是向模型添加一个额外的属性:
The easiest way is to just add an extra property to the model:
@property
def image_url_with_default(self):
return self.image_url or whatever_the_default_url_is
这篇关于Django模型字段,替代值返回如果为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文