Django / SQLite用户模型UNIQUE约束失败

时间:2015-03-19 10:52:16

标签: python django sqlite web-development-server

我正在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很新。所以表现得相应。谢谢你的时间。

1 个答案:

答案 0 :(得分:4)

将关系设置为user = models.OneToOneField(User)意味着每Change只能有一个User

将其更改为:

user = models.ForeignKey(User)