Search code examples
pythondjangodjango-mptt

How to populate inherited MPTT fields while creating a Django fixture?


I'm following the instructions here to create my first Django fixture. I've created a JSON file. But there is a complication: The model I'm trying to populate inherits from MPTTModel

Here is what my Django JSON fixture file initial_data.json looks like:

[
    {
         "model": "MyApp.MyModel", 
         "pk": 1, 
         "fields": {
             "level": 0, 
             "parent": null, 
             "name": "My String"
         }
    }
]

When I run this fixture, I get the error shown below. It turns out there are a handful of other fields that must be defined in the fixture for this model: rght, lft, tree_id, level.

django.db.utils.IntegrityError: Problem installing fixture    
'MyApp/fixtures/initial_data.json': Could not load MyApp.MyModel(pk=1): 
    null value in column "lft" violates not-null constraint
Failing row contains (1, My String, null, , null, null, null, 0).

I can figure out what the level attribute is supposed to be and insert it into the fixture file. But how am I supposed to figure out and set the values of rght, lft, tree_id in the this fixture?


Solution

  • how did you create the fixture, manually? using the dumpdata command should give you a clear view of the required structure, here's an example of a mptt inheriting model json dump:

    $ ./manage.py dumpdata cms.Page --natural --indent=4
    [
        {
            "pk": 46,
            "model": "cms.page",
            "fields": {
                "rght": 43,
                "navigation_extenders": "",
                "site": 1,
                "creation_date": "2014-05-31T12:07:12Z",
                "lft": 42,
                "in_navigation": false,
                "reverse_id": null,
                "login_required": false,
                "created_by": "hedde",
                "publication_end_date": null,
                "template": "cms/page.html",
                "tree_id": 2,
                "placeholders": [
                    159,
                    160
                ],
                "changed_date": "2014-06-25T09:33:50Z",
                "limit_visibility_in_menu": null,
                "parent": 2,
                "publisher_state": 0,
                "soft_root": false,
                "publication_date": "2014-05-31T12:07:07Z",
                "publisher_public": 45,
                "level": 1,
                "changed_by": "hedde",
                "publisher_is_draft": false,
                "published": true
            }
        }
    ]