Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Map data from an external APIs into a model?

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?

like image 688
simonwjackson Avatar asked Nov 16 '13 14:11

simonwjackson


1 Answers

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))
like image 115
ndpu Avatar answered Nov 15 '22 05:11

ndpu