django - 不立即保存到数据库
又是一个新手问题,
我在把一个项目保存到数据库后,想获取它的主键(就是唯一标识这个项目的编号),然后用这个主键来重定向到它的页面。但是我没有成功。
我尝试按照这个 文档 的说明手动处理事务,但还是不行。
这可能是因为我在使用管理员模式吗?
我遇到了这个错误:
invalid literal for int() with base 10: 'None'
我把返回的那行代码改成了这样,以便把 id 转换成字符串
return HttpResponseRedirect("/blog/page/"+str(page.id)+"/")
这是代码的一部分。
@transaction.commit_manually
def new_post_save(request):
.
.
.
page.save()
sid = transaction.savepoint()
transaction.savepoint_commit(sid)
return HttpResponseRedirect("/blog/page/"+page.id+"/")
这是原始视图和模型的其余部分。
def new_post_save(request):
page_name = request.POST["page_name"]
content = request.POST["content"]
postCategory = request.POST["cat"]
page = BlogPost(title = page_name,body = content, author = request.user, category = postCategory)
page.save()
return HttpResponseRedirect("/blog/page/"+page.id+"/")
这是模型。
class BlogPost(models.Model):
id = models.IntegerField(primary_key=True)
author = models.ForeignKey(User)
title = models.CharField(max_length=128)
body = models.TextField()
category = models.CharField(max_length=10, default='other')
def __unicode__(self):
return self.title
在 base.py 中,我想我没有重写保存函数。
def save(self, force_insert=False, force_update=False, using=None):
"""
Saves the current instance. Override this in a subclass if you want to
control the saving process.
The 'force_insert' and 'force_update' parameters can be used to insist
that the "save" must be an SQL insert or update (or equivalent for
non-SQL backends), respectively. Normally, they should not be set.
"""
if force_insert and force_update:
raise ValueError("Cannot force both insert and updating in model saving.")
self.save_base(using=using, force_insert=force_insert, force_update=force_update)
save.alters_data = True
在 settings.py 中关于数据库的设置。
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'blog.db',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
2 个回答
0
用这个方法代替手动调用保存功能。
page = BlogPost.objects.create(title = page_name, body = content, author = request.user, category = postCategory)
5
把你的模型类中的 id
字段去掉。
如果你没有指定主键,Django 会自动插入一个叫 id
的自动编号字段,所以你其实不需要自己写这个字段。
因为你特别说明了 你的 id
字段是一个整数主键,Django 就会期待你自己来管理这个字段。它是你声明的 IntField
,而不是 AutoField
,所以它不会自动给你分配任何值。