168👍
manage.py dumpdata --natural
will use a more durable representation of foreign keys. In django they are called “natural keys”. For example:
Permission.codename
is used in favour ofPermission.id
User.username
is used in favour ofUser.id
Read more: natural keys section in “serializing django objects”
Some other useful arguments for dumpdata
:
--indent=4
make it human readable.-e sessions
exclude session data-e admin
exclude history of admin actions on admin site-e contenttypes -e auth.Permission
exclude objects which are recreated automatically from schema every time duringsyncdb
. Only use it together with--natural
or else you might end up with badly aligned id numbers.
50👍
The answers here all old… As of 2017, the best answer is:
manage.py dumpdata --natural-foreign --natural-primary -e contenttypes -e auth.Permission --indent 4
- [Django]-Django FileField with upload_to determined at runtime
- [Django]-Creating a JSON response using Django and Python
- [Django]-South migration: "database backend does not accept 0 as a value for AutoField" (mysql)
36👍
Yes, this is really irritating. For a while I worked around it by doing a “manage.py reset” on the contenttypes app prior to loading the fixture (to get rid of the automatically-generated contenttypes data that differed from the dumped version). That worked, but eventually I got sick of the hassles and abandoned fixtures entirely in favor of straight SQL dumps (of course, then you lose DB portability).
update – the best answer is to use the --natural
flag to dumpdata
, as noted in an answer below. That flag did not exist yet when I wrote this answer.
- [Django]-Using JSON in django template
- [Django]-How do I perform HTML decoding/encoding using Python/Django?
- [Django]-How to assign items inside a Model object with Django?
34👍
Try skipping contenttypes when creating fixture:
./manage.py dumpdata --exclude contenttypes > fixture.json
It worked for me in a similar situation for unit tests, your insight regarding the contenttypes really helped!
- [Django]-Where to put business logic in django
- [Django]-Getting Django admin url for an object
- [Django]-Django development IDE
16👍
I was not using MySQL but instead importing some data from a live server into sqlite. Clearing the contenttypes
app data before performing loaddata
did the trick:
from django.contrib.contenttypes.models import ContentType
ContentType.objects.all().delete()
quit()
And then
python manage.py loaddata data.json
- [Django]-How to make an auto-filled and auto-incrementing field in django admin
- [Django]-How to use permission_required decorators on django class-based views
- [Django]-Where's my JSON data in my incoming Django request?
10👍
I have resolved this issue in my test cases by resetting the contenttypes app from the unit test prior to loading my dump file. Carl suggested this already using the manage.py
command and I do the same thing only using the call_command
method:
>>> from django.core import management
>>> management.call_command("flush", verbosity=0, interactive=False)
>>> management.call_command("reset", "contenttypes", verbosity=0, interactive=False)
>>> management.call_command("loaddata", "full_test_data.json", verbosity=0)
My full_test_data.json
fixture contains the contenttypes app dump that corresponds to the rest of the test data. By resetting the app before loading, it prevents the duplicate key IntegrityError
.
- [Django]-Django simple_tag and setting context variables
- [Django]-What is a "django backend"?
- [Django]-Django-debug-toolbar not showing up
8👍
You need to use natural keys to represent any foreign key and many-to-many relationships. Moreover, it might be a good idea to exclude the session
table in the sessions
app, and the logentry
table in the admin
app.
Django 1.7+
python manage.py dumpdata --natural-foreign --exclude contenttypes --exclude auth.permission --exclude admin.logentry --exclude sessions.session --indent 4 > fixture.json
Django <1.7
python manage.py dumpdata --natural --exclude contenttypes --exclude auth.permission --exclude admin.logentry --exclude sessions.session --indent 4 > fixture.json
According to the Django documentation, --natural
has been deprecated in version 1.7, so the option --natural-foreign
should be used instead.
You can also omit the primary key in the serialized data of this object since it can be calculated during deserialization by passing the --natural-primary
flag.
python manage.py dumpdata --natural-foreign --natural-primary --exclude contenttypes --exclude auth.permission --exclude admin.logentry --exclude sessions.session --indent 4 > fixture.json
- [Django]-Allowing only super user login
- [Django]-Django: accessing session variables from within a template?
- [Django]-How can I see the raw SQL queries Django is running?
7👍
python manage.py dumpdata --natural-primary --exclude=contenttypes --exclude=auth.Permission --exclude=admin.logentry --exclude=sessions.session --indent 4 > initial_data.json
This works for me. Here I am excluding everything bubt the actual models.
- If you see any other model other than the models that you created you can safely exclude those. One drawback of this approach is you loose on log data as well as auth data.
- [Django]-Django 2.0 – Not a valid view function or pattern name (Customizing Auth views)
- [Django]-Converting Django QuerySet to pandas DataFrame
- [Django]-What is the difference between null=True and blank=True in Django?
4👍
./manage.py dumpdata app.Model --natural-foreign
will change
"content_type": 123
to
"content_type": [
"app_label",
"model"
],
And fixture works for TestCase
now
- [Django]-How can i test for an empty queryset in Django?
- [Django]-">", "<", ">=" and "<=" don't work with "filter()" in Django
- [Django]-Why is __init__ module in django project loaded twice
3👍
Django 2.2.5
python manage.py dumpdata --exclude=contenttypes > datadump.json
it helped me
- [Django]-Add rich text format functionality to django TextField
- [Django]-NumPy array is not JSON serializable
- [Django]-Auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'UserManage.groups'
2👍
It’s really, really annoying .. I get bitten by this every single time.
I tried to dumpdata with –exclude contenttypes and –natural, I always get problems..
What works best for me is simply doing a truncate table django_content_type;
after the syncdb and THEN load the data.
Of course for initial_data.json autoloading you’re fallball.
- [Django]-Changing a project name in django
- [Django]-How to override and extend basic Django admin templates?
- [Django]-What's the difference between select_related and prefetch_related in Django ORM?
1👍
I’m going to give another possible answer that I just figured out. Maybe it’ll help the OP, maybe it’ll help somebody else.
I’ve got a many-to-many relationship table. It has a primary key and the two foreign keys to the other tables. I found that if I have an entry in the fixture whose two foreign keys are the same as another entry already in the table with a different pk, it will fail. M2M relationship tables have a “unique together” for the two foreign keys.
So, if it’s a M2M relationship that is breaking, look at the foreign keys it’s adding, look at your database to see if that pair of FKs are already listed under a different PK.
- [Django]-How to convert a Django QuerySet to a list?
- [Django]-How to disable admin-style browsable interface of django-rest-framework?
- [Django]-Django MultiValueDictKeyError error, how do I deal with it
1👍
I had encountered similar error sometimes ago. It turned out that I was trying to load the fixtures before creating the necessary tables. So I did:
$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py loaddata fixtures/initial_data.json
And it worked like a charm
- [Django]-Django models: get list of id
- [Django]-Django – How to pass several arguments to the url template tag
- [Django]-Sending images using Http Post
1👍
I tried every method from above, Nothing worked for me. I have to exclude the complete auth model and works fine.
python manage.py dumpdata --natural-primary --exclude=contenttypes --exclude=auth --exclude=admin.logentry --exclude=sessions.session --indent 4 > live.json
- [Django]-Malformed Packet: Django admin nested form can't submit, connection was reset
- [Django]-Django custom management commands: AttributeError: 'module' object has no attribute 'Command'
- [Django]-Temporarily disable auto_now / auto_now_add
0👍
In my case I had dumped the data from auth
(./manage.py dumpddata auth > fixtures/auth.json
) to use the fixture for testing purposes.
The development continued and I removed most of the models I had defined in models.py
and this is when I started to see this annoying problem.
My solution was regenerating the auth.json fixture again. This one had removed lots of entries in auth.permission
related to the old models I had.
- [Django]-How do I do a not equal in Django queryset filtering?
- [Django]-Easiest way to rename a model using Django/South?
- [Django]-Creating email templates with Django
0👍
I’ve fixed this by adding in my tests setUp and tearDown
from django.core import management
=====
def setUp(self):
management.call_command("loaddata", "all-data.yaml", verbosity=0)
super(login_page_test, self).setUp()
def tearDown(self):
management.call_command("flush", verbosity=0, interactive=False)
super(login_page_test, self).setUp()
- [Django]-What's the purpose of Django setting ‘SECRET_KEY’?
- [Django]-Django: Redirect to previous page after login
- [Django]-Ignoring Django Migrations in pyproject.toml file for Black formatter
0👍
I used pgloader, just take a few seconds to migrate successfully:
$ pgloader project.load
project.load file with:
load database
from sqlite:////path/to/dev.db
into postgresql://user:pwd@localhost/db_name
with include drop, create tables, create indexes, reset sequences
set work_mem to '16MB', maintenance_work_mem to '512 MB';
- [Django]-Using JSON in django template
- [Django]-What is the SQL ''LIKE" equivalent on Django ORM queries?
- [Django]-What are the limitations of Django's ORM?