伙计们我得到一个错误,因为你应该对模型有一个默认值:author,body,created,updated 这是我的models.py配置
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
# Create your models here.
class post(models.Model):
STATUS_CHOICE=(
('draft','DRAFT'),
('published','Published'),
)
title=models.CharField(max_length=250)
slug=models.SlugField(max_length = 250,unique_for_date=1)
author=models.ForeignKey(User,related_name='blog_posts')
body=models.TextField()
publish=models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated=models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10,
choices = STATUS_CHOICE,
default='draft')
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
这是迁移数据库时的错误:
You are trying to add a non-nullable field 'body' to post without a default; we can't do that (the database needs something to populate
existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option
我不确定这些型号的默认值是什么,配置与书中提到的相同,但我仍然收到错误 任何形式的帮助表示赞赏 提前致谢 注意:这是一个博客应用程序 当我试图向模型添加随机默认值时,我收到此错误: 更新了models.py:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
# Create your models here.
class post(models.Model):
STATUS_CHOICE=(
('draft','DRAFT'),
('published','Published'),
('admin','admin'),
)
title=models.CharField(max_length=250)
slug=models.SlugField(max_length = 250)
author=models.ForeignKey(User,related_name='blog_posts')
body=models.TextField(default='draft')
publish=models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True,default=timezone.now)
updated =models.DateTimeField(auto_now=True,default=timezone.now)
status = models.CharField(max_length=10,
choices = STATUS_CHOICE,
default='draft')
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
现在的错误是:
ERRORS:
myblog.post.created: (fields.E160) The options auto_now, auto_now_add, and default are mutually exclusive. Only one of these options may
be present.
myblog.post.updated: (fields.E160) The options auto_now, auto_now_add, and default are mutually exclusive. Only one of these options may
be present
答案 0 :(得分:1)
为什么不使用null = True,blank = True - 允许模型属性为空!
我会将body属性的默认值设置为''
body=models.TextField(default='')
时间戳不应该有默认值,你提供的callables应该足够了。
# Model Timestamp
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
执行迁移时,它会为创建和更新的属性运行缺少的默认错误,请选择1)并在控制台中输入
timezone.now()
。这会将现有行的默认值设置为当前日期时间。