【问题标题】:IntegrityError when loading fixture during django testing在 Django 测试期间加载夹具时出现 IntegrityError
【发布时间】:2023-03-16 05:01:02
【问题描述】:

我正在加载使用转储数据创建的夹具,并收到以下异常:

Problem installing fixture 'db_dump.json': Traceback (most recent call last):
  File "/usr/lib/python2.6/site-packages/django/core/management/commands/loaddata.py", line 174, in handle
    obj.save(using=using)
  File "/usr/lib/python2.6/site-packages/django/core/serializers/base.py", line 165, in save
    models.Model.save_base(self.object, using=using, raw=True)
  File "/usr/lib/python2.6/site-packages/django/db/models/base.py", line 526, in save_base
    rows = manager.using(using).filter(pk=pk_val)._update(values)
  File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 491, in _update
    return query.get_compiler(self.db).execute_sql(None)
  File "/usr/lib/python2.6/site-packages/django/db/models/sql/compiler.py", line 869, in execute_sql
    cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
  File "/usr/lib/python2.6/site-packages/django/db/models/sql/compiler.py", line 735, in execute_sql
    cursor.execute(sql, params)
  File "/usr/lib/python2.6/site-packages/django/db/backends/sqlite3/base.py", line 234, in execute
    return Database.Cursor.execute(self, query, params)
IntegrityError: columns app_label, model are not unique

这是一个 sqlite3 后端。

更新:使用自然键在这里没有什么不同。

这是什么意思,为什么会这样?

【问题讨论】:

    标签: django django-testing django-fixtures


    【解决方案1】:

    显然,粗心的陷阱之一是在导出固定装置时必须排除内容类型。 (感谢 #django 上的 subsume 提供信息)。

    要排除内容类型,请在运行 dumpdata 命令时使用-e 选项。

    $./manage.py dumpdata -e contenttypes > initial_data.json
    

    【讨论】:

    • 是的,被那个击中了几次,尽管只是在将开发数据库从一个引擎迁移到另一个引擎时。测试夹具的一般规则是您应该确切地知道其中的内容,这样您就知道测试中发生了什么,所以您不会有任何意外。
    • 这样的东西对我有用(仅供参考):./manage.py dumpdata -e contenttypes > initial_data.json .
    【解决方案2】:
    python manage.py dumpdata --exclude=contenttypes --exclude=auth.Permission > initial_data.json
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-21
      • 2011-04-18
      • 1970-01-01
      • 2013-10-24
      • 1970-01-01
      • 2018-02-07
      • 2011-01-12
      • 2015-02-14
      相关资源
      最近更新 更多