简体   繁体   中英

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

I just changed my pk name in a model.

This is how my model was:

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)

As you can see I didnt specified the PK but I changed that:

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)

As you can see now "reference" is my pk but when I try to install this fixture:

[{
        "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
        }
    },

I receive the next error:

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':

Why is this happening?

In your example, you are using the plural "models" instead of "model" in the fixture keys.

"models": "consumptions.course",

should be:

"model": "consumptions.course",

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM