13

I'm using django's ContentType foreign key in my model, and I'm using it in the fixtures for unit tests.

Therefore, I have to hard-code content_type_id in my fixture, but django sometimes initializes it to a different value and thus my tests fail.

So is there a way to safely predict the content_type_id of the model or any other proper way to handle such situations?

dragoon
  • 5,601
  • 5
  • 37
  • 55

1 Answers1

20

Use natural keys: https://docs.djangoproject.com/en/dev/topics/serialization/#natural-keys

Most of the documentation refers to how to add the capability to your own models, but ContentType already supports them so just add --natural-foreign to your dumpdata management command:

$ python manage.py dumpdata myapp --indent=4 --natural-foreign
Janusz Skonieczny
  • 17,642
  • 11
  • 55
  • 63
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • 2
    Thanks, a note that ``ContentType`` already have ``get_by_natural_key(app_label, model)`` is very useful. – dragoon Nov 08 '11 at 15:20
  • Thanks, was stumped on this for a while. Also needed "--natural-primary" to get testing working. – hoju Nov 28 '16 at 09:49