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?
Django includes a contenttypes application that can track all of the models installed in your Django-powered project, providing a high-level, generic interface for working with your models.
A fixture is a collection of data that Django knows how to import into a database. The most straightforward way of creating a fixture if you've already got some data is to use the manage.py dumpdata command.
The preferred way to write tests in Django is using the unittest module built-in to the Python standard library. This is covered in detail in the Writing and running tests document. You can also use any other Python test framework; Django provides an API and tools for that kind of integration.
The request factory The API for the RequestFactory is a slightly restricted subset of the test client API: It only has access to the HTTP methods get() , post() , put() , delete() , head() , options() , and trace() . These methods accept all the same arguments except for follow .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With