1

I'm working on a Django project using a noSQL database MongoDB. I have the data I need to populate the database with stored in a JSON file, but I can't figure out how to do it. The model, which I'm trying to have a one to many relationship with other objects of the same class:

class Hero(models.Model):

    name        = models.TextField(max_length=120, null=True)    
    counters    = models.ForeignKey('self', null=True, on_delete=models.CASCADE)
    image       = models.ImageField(blank=False, null=True, upload_to="")

And the example of my JSON file data:


{  
   "Abaddon":{  
      "counters":[  
         "Ancient Apparition",
         "Brewmaster",
         "Doom",
         "Outworld Devourer",
         "Shadow Demon"
      ],
      "image":"media/Abaddon.png"
   },...

Do I need to format the JSON data differently? I'm at a loss here.

Marc
  • 49
  • 8
  • Possible duplicate of [Django saving json value to database/model](https://stackoverflow.com/questions/36123877/django-saving-json-value-to-database-model) – Aurélien Apr 27 '19 at 12:06

1 Answers1

2

Yes, you can import initial data from JSON using fixtures. However you'll have to format your JSON differently of course. Otherwise you'll have to make a script yourself to parse it and add data to your database.

Antoine Pinsard
  • 33,148
  • 8
  • 67
  • 87
  • Is there a proper way to specify ImageField data through fixtures? I can't find it in the documentation. Thanks so much for the quick reply! – Marc Apr 28 '19 at 07:18
  • Yes. Checkout [this answer](https://stackoverflow.com/a/5726226/1529346) – Antoine Pinsard Apr 28 '19 at 17:29