Default value for field in Django model

前端 未结 3 805
长发绾君心
长发绾君心 2020-12-02 08:58

Suppose I have a model:

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


        
相关标签:
3条回答
  • 2020-12-02 09:12

    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.

    0 讨论(0)
  • 2020-12-02 09:17

    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'
    
    0 讨论(0)
  • 2020-12-02 09:26

    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")
    
    0 讨论(0)
提交回复
热议问题