I am pulling in some JSON data from various external APIs. Their data may be structured like this:
"game": {
"title": "Super Mario Bros. 3",
"release": "1989",
"players": 3,
..
}
However, I'd like to store this directly in my database via this model:
class Game(models.Model):
name = models.CharField()
debut = models.DateField()
max_players = models.IntegerField()
As you can tell, the JSON attributes don't match up to the model's attributes.
Is there a clean way to map each attribute to easily import this data? Is it possible do do this through django's deserialization module? Or will I need to create something of my own?
You can create classmethod (or place it in model manager https://docs.djangoproject.com/en/dev/ref/models/instances/#creating-objects):
class Game(models.Model):
name = models.CharField()
debut = models.DateField()
max_players = models.IntegerField()
@classmethod
def create_from_j(cls, game): # assumed that game is dict already
j2m = {'title': 'name', 'release': 'debut', 'players': 'max_players'}
return cls(**{j2m[k]:v for k,v in game.items()})
just call this method then you need to create a Game from json data:
game = Game.create_from_j(json.loads(json_game))
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