DJANGO:当主键不是 "id" 时如何在 fixture 中指定主键

DJANGO: How to specify primary key in fixture when the primary key is not "id"

我刚刚更改了模型中的 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':

为什么会这样?

在您的示例中,您在灯具键中使用了复数“models”而不是“model”。

"models": "consumptions.course",

应该是:

"model": "consumptions.course",