问题:Django模型中字段的默认值

假设我有一个模型:

class SomeModel(models.Model):
    id = models.AutoField(primary_key=True)
    a = models.CharField(max_length=10)
    b = models.CharField(max_length=7)

目前,我正在使用默认的admin创建/编辑此类型的对象。如何从管理员中删除该字段,以使每个对象都无法创建一个值,而是会收到默认值0000000

Suppose I have a model:

class SomeModel(models.Model):
    id = models.AutoField(primary_key=True)
    a = models.CharField(max_length=10)
    b = models.CharField(max_length=7)

Currently I am using the default admin to create/edit objects of this type. How do I remove the field from the admin so that each object cannot be created with a value, and rather will receive a default value of 0000000?


回答 0

设置editableFalsedefault为默认值。

http://docs.djangoproject.com/en/stable/ref/models/fields/#editable

b = models.CharField(max_length=7, default='0000000', editable=False)

另外,您的id字段是不必要的。Django将自动添加它。

Set editable to False and default to your default value.

http://docs.djangoproject.com/en/stable/ref/models/fields/#editable

b = models.CharField(max_length=7, default='0000000', editable=False)

Also, your id field is unnecessary. Django will add it automatically.


回答 1

您可以这样设置默认值:

b = models.CharField(max_length=7,default="foobar")

然后您可以使用模型的Admin类隐藏字段,如下所示:

class SomeModelAdmin(admin.ModelAdmin):
    exclude = ("b")

You can set the default like this:

b = models.CharField(max_length=7,default="foobar")

and then you can hide the field with your model’s Admin class like this:

class SomeModelAdmin(admin.ModelAdmin):
    exclude = ("b")

回答 2

您还可以在默认字段中使用callable,例如:

b = models.CharField(max_length=7, default=foo)

然后定义可调用项:

def foo():
    return 'bar'

You can also use a callable in the default field, such as:

b = models.CharField(max_length=7, default=foo)

And then define the callable:

def foo():
    return 'bar'

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。