如何创建一个具有默认值(如果设置为null)的django模型字段 [英] How to create a django model field that has a default value if ever set to null

查看:1797
本文介绍了如何创建一个具有默认值(如果设置为null)的django模型字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个模型

class Template(models.Model):
    colour = models.CharField(default="red", blank = True, null=True)

我如何安排它,以便任何访问颜色还是返回存储在字段中的值,或者如果该字段为空/空,那么它返回红色?

How can I arrange it so that any access to colour either returns the value stored in the field, or if the field is blank/null then it returns red?

default=red

将在首次创建时将字段中的红,但如果它被编辑为空白我想要访问它返回红色,而不是

will put "red" in the field when it's first created, but if it's then edited to blank I'd like access to it to return "red", not ""

更新:我尝试了以下建议的属性解决方案,但是我使用JSON序列化来实现REST API和属性(例如 color )没有序列化,序列化 _colour 打破API

Updated: I tried the properties solution suggested below, but I'm using JSON serialisation to implement a REST API and the properties (e.g. colour) don't get serialised, and serialising the _colour breaks the API

推荐答案

以下是我如何解决这个问题。

Here's how I ended up solving this problem.

首先有一些前提条件:我有现有的代码访问这些字段名称(例如'color')和th e字段也被序列化(由django-rest-interface)作为API的一部分。这些东西都不能改变。

First some preconditions: I have existing code that accesses these field names (e.g. 'colour') and the field is also serialised (by django-rest-interface) as part of an API. Neither of these things can be changed.

尝试属性方法工作正常,除了 color 不再是字段没有被序列化。结果:破坏的API

Trying the properties method worked fine, except that colour was no longer a field so didn't get serialised. Result: broken API

然后移动到save()解决方案,以及每个字段的自定义属性应该如下所示:

Then moved to the save() solution, along with a custom attribute on each field which should behave like this:

class ColourChoices(models.Model):
    colour1 = models.CharField()
    colour1.colour_default = "red"
    colour2 = models.CharField()
    colour2.colour_default = "blue"

    def save(self, *args, **kwargs):
        # force colour fields to default values
        for f in [ x for x in self._meta.fields if hasattr(x, 'colour_default') ]:
            if self.__getattribute__(f.attname) == "":
                self.__setattr__(f.attname, f.colour_default)
       super(ColourChoices, self).save(*args,**kwargs)

现在都可以正常工作,并且根据需要。

Now all works fine and as required.

此解决方案的唯一问题是,如果默认值更改是不可能的告诉哪些数据库字段应该具有更新的默认值,哪些是j呃意外地和旧的默认的颜色一样。但是,对于我的申请,我可以和他一起生活。

The only problem with this solution is that if the default values change it's impossible to tell which database fields should have updated defaults, and which are just accidentally the same colour as the old default. However for my application I can live with this.

这篇关于如何创建一个具有默认值(如果设置为null)的django模型字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆