Django/SQLite 用户模型 UNIQUE 约束失败
Django/SQLite User model UNIQUE constraint failed
我正在用 Django 实现一个项目。简而言之,有用户和项目以及哪个用户在哪个项目上工作的日志(称为更改)。问题是排除用户第一次进行更改(与项目无关),我收到 UNIQUE constraint failed
错误。正如您将看到的,验证在 change.user_id 中失败。但这不是主键,因为 SQLite 会自动声明一个。
注意:我使用的是Django内置的用户模型。
错误日志:
Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python34\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
21. return view_func(request, *args, **kwargs)
File "C:\Users\George II\OneDrive\IC3D Media\ProjectLogging\views.py" in main
42. change.save()
File "C:\Python34\lib\site-packages\django\db\models\base.py" in save
589. force_update=force_update, update_fields=update_fields)
File "C:\Python34\lib\site-packages\django\db\models\base.py" in save_base
617. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Python34\lib\site-packages\django\db\models\base.py" in _save_table
698. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Python34\lib\site-packages\django\db\models\base.py" in _do_insert
731. using=using, raw=raw)
File "C:\Python34\lib\site-packages\django\db\models\manager.py" in manager_method
92. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python34\lib\site-packages\django\db\models\query.py" in _insert
921. return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Python34\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
920. cursor.execute(sql, params)
File "C:\Python34\lib\site-packages\django\db\backends\utils.py" in execute
81. return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python34\lib\site-packages\django\db\backends\utils.py" in execute
65. return self.cursor.execute(sql, params)
File "C:\Python34\lib\site-packages\django\db\utils.py" in __exit__
94. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python34\lib\site-packages\django\utils\six.py" in reraise
658. raise value.with_traceback(tb)
File "C:\Python34\lib\site-packages\django\db\backends\utils.py" in execute
65. return self.cursor.execute(sql, params)
File "C:\Python34\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
485. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /main/
Exception Value: UNIQUE constraint failed: ProjectLogging_change.user_id
models.py:
from django.db import models
from sqlalchemy.dialects.sqlite import BOOLEAN
from django.contrib.auth.models import User
class Project(models.Model):
title=models.CharField(max_length=200,db_index=True)
def get_id(self):
try:
return unicode(self.id)
except NameError:
return str(self.id)
def __repr__(self):
return ('Project %r: %r' % (str(self.id), self.title))
def __unicode__(self):
return ('Project %r: %r' % (str(self.id), self.title))
class Change(models.Model):
user=models.OneToOneField(User)
project=models.ForeignKey('Project')
starttime=models.DateTimeField(null=True,blank=True)
endtime=models.DateTimeField(null=True, blank=True)
flagged=models.BooleanField(default=False, db_index=True)
def __repr__(self):
return ('Change in project %r from %r' % (self.project.title, self.user.username))
def user_changes(self, user):
return self.filter(user==user)
对应查看:
def main(request):
context = RequestContext(request)
user=request.user
if request.method=='POST':
projectid=request.POST['project']
project = Project.objects.get(pk=int(projectid))
if project:
change=Change(user=user, project=project,starttime=datetime.now())
change.save()
return HttpResponse("I \'ve already start counting... You \'ve wasted 5 seconds already.")
else:
HttpResponse("Choose a valid project!")
else:
HttpResponse("Choose a POST method (???????)")
很明显我是 Django 和 python 的新手。所以要相应地行事。谢谢你的时间。
设置关系为user = models.OneToOneField(User)
表示每个User
.
只能有一个Change
改为:
user = models.ForeignKey(User)
我正在用 Django 实现一个项目。简而言之,有用户和项目以及哪个用户在哪个项目上工作的日志(称为更改)。问题是排除用户第一次进行更改(与项目无关),我收到 UNIQUE constraint failed
错误。正如您将看到的,验证在 change.user_id 中失败。但这不是主键,因为 SQLite 会自动声明一个。
注意:我使用的是Django内置的用户模型。
错误日志:
Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python34\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
21. return view_func(request, *args, **kwargs)
File "C:\Users\George II\OneDrive\IC3D Media\ProjectLogging\views.py" in main
42. change.save()
File "C:\Python34\lib\site-packages\django\db\models\base.py" in save
589. force_update=force_update, update_fields=update_fields)
File "C:\Python34\lib\site-packages\django\db\models\base.py" in save_base
617. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Python34\lib\site-packages\django\db\models\base.py" in _save_table
698. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Python34\lib\site-packages\django\db\models\base.py" in _do_insert
731. using=using, raw=raw)
File "C:\Python34\lib\site-packages\django\db\models\manager.py" in manager_method
92. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python34\lib\site-packages\django\db\models\query.py" in _insert
921. return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Python34\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
920. cursor.execute(sql, params)
File "C:\Python34\lib\site-packages\django\db\backends\utils.py" in execute
81. return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python34\lib\site-packages\django\db\backends\utils.py" in execute
65. return self.cursor.execute(sql, params)
File "C:\Python34\lib\site-packages\django\db\utils.py" in __exit__
94. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python34\lib\site-packages\django\utils\six.py" in reraise
658. raise value.with_traceback(tb)
File "C:\Python34\lib\site-packages\django\db\backends\utils.py" in execute
65. return self.cursor.execute(sql, params)
File "C:\Python34\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
485. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /main/
Exception Value: UNIQUE constraint failed: ProjectLogging_change.user_id
models.py:
from django.db import models
from sqlalchemy.dialects.sqlite import BOOLEAN
from django.contrib.auth.models import User
class Project(models.Model):
title=models.CharField(max_length=200,db_index=True)
def get_id(self):
try:
return unicode(self.id)
except NameError:
return str(self.id)
def __repr__(self):
return ('Project %r: %r' % (str(self.id), self.title))
def __unicode__(self):
return ('Project %r: %r' % (str(self.id), self.title))
class Change(models.Model):
user=models.OneToOneField(User)
project=models.ForeignKey('Project')
starttime=models.DateTimeField(null=True,blank=True)
endtime=models.DateTimeField(null=True, blank=True)
flagged=models.BooleanField(default=False, db_index=True)
def __repr__(self):
return ('Change in project %r from %r' % (self.project.title, self.user.username))
def user_changes(self, user):
return self.filter(user==user)
对应查看:
def main(request):
context = RequestContext(request)
user=request.user
if request.method=='POST':
projectid=request.POST['project']
project = Project.objects.get(pk=int(projectid))
if project:
change=Change(user=user, project=project,starttime=datetime.now())
change.save()
return HttpResponse("I \'ve already start counting... You \'ve wasted 5 seconds already.")
else:
HttpResponse("Choose a valid project!")
else:
HttpResponse("Choose a POST method (???????)")
很明显我是 Django 和 python 的新手。所以要相应地行事。谢谢你的时间。
设置关系为user = models.OneToOneField(User)
表示每个User
.
Change
改为:
user = models.ForeignKey(User)