How to load fixtures.json with ManyToMany Relationships in Django

Viewed 353

Let's say you have to create a database where you store all the books from a library and all the authors from the world. You have every book in file named books.json and every author in a file named authors.json Then you want to create a link between those to tables where a book can have one or more authors. What I did is I created needed models, then I loaded authors.json and then when I try to load books.json I got the error: django.core.serializers.base.DeserializationError: Problem installing fixture '/workspace/libray/books/fixtures/books.json':

class book(models.Model):
     name =models.CharField(max_length=254, blank=True, null=True, on_delete=SET_NULL)
     authors = models.ManyToManyField(author)



class authors(models.Model):
        name = models.Charfield(max_length=100, blank=True, null=True, on_delete=SET_NULL)


   books.json
[ 
   {
    "pk":1,
    "model":books.book,
    "fields":{
              "name":"Book1",
              "authors":[1,2,3]
              }
    },
    ...
 ]

authors.json
[ 
   {
    "pk":1,
    "model":books.author,
    "fields":{
              "name":"Author1",
            }
    },
    ...
 ]

How to load properly some fixtures when there are M2M relationships between models.

1 Answers

Firstly add some test data in your models, then run python manage.py dumpdata myapp > somefile.json

Then voila you have your fixture template.

Related