DJANGO:当主键不是“id”时如何在夹具中指定主键

Posted

技术标签:

【中文标题】DJANGO:当主键不是“id”时如何在夹具中指定主键【英文标题】:DJANGO: How to specify primary key in fixture when the primary key is not "id" 【发布时间】:2021-03-12 09:05:06 【问题描述】:

我刚刚在模型中更改了我的 pk 名称。

我的模型是这样的:

class Course(LogsMixin, models.Model):
    """Definición del modelo de Proveedor."""
    name = models.CharField("Nombre del curso", null=False, default="", max_length=200)
    code = models.CharField("Código del curso", null=False, default="", max_length=50)
    hours = models.IntegerField(("Número de horas"), null=False, default=0)
    price = models.DecimalField(("Precio"), max_digits=6, decimal_places=2, null=False, default=0)
    provider = models.ForeignKey(Provider, verbose_name=("Proveedor"), null=True, default=None, on_delete=models.SET_DEFAULT)
    active = models.BooleanField("Activo", default=True)

如您所见,我没有指定 PK,但我更改了:

class Course(LogsMixin, models.Model):
    """Definición del modelo de Proveedor."""
    reference = models.CharField("Referencia", primary_key=True, null=False, default="", max_length=50)
    name = models.CharField("Nombre del curso", null=False, default="", max_length=200)
    code = models.CharField("Código del curso", null=False, default="", max_length=50)
    hours = models.IntegerField(("Número de horas"), null=False, default=0)
    price = models.DecimalField(("Precio"), max_digits=6, decimal_places=2, null=False, default=0)
    provider = models.ForeignKey(Provider, verbose_name=("Proveedor"), null=True, default=None, on_delete=models.SET_DEFAULT)
    active = models.BooleanField("Activo", default=True)

正如你现在看到的,“参考”是我的 pk,但是当我尝试安装这个夹具时:

[
        "models": "consumptions.course",
        "pk": "AD_ADGD008PO",
        "fields": 
            "name": "ANÁLISIS DE PROBLEMAS Y TOMA DE DECISIONES",
            "code": "ADGD008PO",
            "price": "21.00",
            "hours": "30",
            "provider": "P000019",
            "active": true
        
    ,

我收到下一个错误:

Traceback (most recent call last):
  File "C:\Users\aquesada\.virtualenvs\AVC-dSHgJ7e5\lib\site-packages\django\core\serializers\json.py", line 69, in Deserializer
    yield from PythonDeserializer(objects, **options)
  File "C:\Users\aquesada\.virtualenvs\AVC-dSHgJ7e5\lib\site-packages\django\core\serializers\python.py", line 92, in Deserializer
    Model = _get_model(d["model"])
KeyError: 'model'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 20, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\aquesada\.virtualenvs\AVC-dSHgJ7e5\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "C:\Users\aquesada\.virtualenvs\AVC-dSHgJ7e5\lib\site-packages\django\core\management\__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\aquesada\.virtualenvs\AVC-dSHgJ7e5\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\aquesada\.virtualenvs\AVC-dSHgJ7e5\lib\site-packages\django\core\management\base.py", line 364, in execute
    output = self.handle(*args, **options)
  File "C:\Users\aquesada\.virtualenvs\AVC-dSHgJ7e5\lib\site-packages\django\core\management\commands\loaddata.py", line 72, in handle
    self.loaddata(fixture_labels)
  File "C:\Users\aquesada\.virtualenvs\AVC-dSHgJ7e5\lib\site-packages\django\core\management\commands\loaddata.py", line 114, in loaddata
    self.load_label(fixture_label)
  File "C:\Users\aquesada\.virtualenvs\AVC-dSHgJ7e5\lib\site-packages\django\core\management\commands\loaddata.py", line 172, in load_label
    for obj in objects:
  File "C:\Users\aquesada\.virtualenvs\AVC-dSHgJ7e5\lib\site-packages\django\core\serializers\json.py", line 73, in Deserializer
    raise DeserializationError() from exc
django.core.serializers.base.DeserializationError: Problem installing fixture 'C:\Users\aquesada\Desktop\Proyectos\AVC\consumptions\fixtures\courses.json':

为什么会这样?

【问题讨论】:

【参考方案1】:

在您的示例中,您在夹具键中使用复数“模型”而不是“模型”。

"models": "consumptions.course",

应该是:

"model": "consumptions.course",

【讨论】:

以上是关于DJANGO:当主键不是“id”时如何在夹具中指定主键的主要内容,如果未能解决你的问题,请参考以下文章

Django之ORM操作

标记一个 Pytest 夹具而不是使用该夹具的所有测试

当主键列不是标识列时如何插入数据?

Django ORM中常用字段和参数

Django ORM中常用字段和参数

如何在 django 中指定索引类型? (btree 与哈希等)