Django id vs pk in fixtures/loaddata

Viewed 129

A strange (to the uninitiated lol) issue with models using a custom CharField for a primary key/id:

id = models.CharField(max_length=10, primary_key=True)

Feeling I know what I'm doing, I've created the following (json) fixtures file:

[
  {
    "model": "products.product",
    "id": "am11",
    "fields": {
      "title": "Test Product A",
    }
  },
  {
    "model": "products.product",
    "id": "am22",
    "fields": {
      "title": "Test Product B",
    }
  }
]

, and proceeded with loading it:

 ✗ python manage.py loaddata fixtures/products.json
Installed 2 object(s) from 1 fixture(s)

Well, it kinda lied. A check on the admin page or in a shell shows that there's only one Product in the database - the last one in the fixture's list. Curiously enough, attempts to delete this Product via the admin page silently fail, only via the shell can it actually be deleted. Further investigation (in the shell) revealed an interesting problem - that (single) Product created has pk/id set to an empty string(?!..but explains why admin fails to delete it). If I manually create another, either on admin page or in the shell, the new product appears without any issues, both id and pk set to the string given. But loaddata with fixture fails on this. Originally discovered this problem when a basic test failed - given the same fixture, in failed the assertion on the number of products in the queryset, claiming there's just one.

Now, I was able to "fix" the problem by renaming 'id' to 'pk' in the fixture file. I say 'fix', because I don't understand what bit me here. Any clue will be appreciated. Thanks!

0 Answers
Related