0

I am a newbie in django world and I'm trying to create a simple rest service with those models:

class Musician(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    instrument = models.CharField(max_length=100)

class Album(models.Model):
    artist = models.ForeignKey(Musician,on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    release_date = models.DateField()
    num_stars = models.IntegerField()

And those serializers:

class MusicianSerializer(serializers.ModelSerializer):
    class Meta:
        model = Musician
        fields = ('id','first_name', 'last_name', 'instrument')

class AlbumSerializer(serializers.ModelSerializer):
    class Meta:
        model = Album
        fields = ('id','artist', 'name', 'release_date', 'num_stars')

I want to be able to post a JSON like this one:

  {
    "first_name": "MusicNom",
    "last_name": "MusicCognom",
    "instrument": "Flauta",
    "albums":
 [
   {
    "name": "Album1",
    "release_date": "2015-02-12",
    "num_stars": 5
  },
  {
    "id": 2,
    "artist": 1,
    "name": "AlbumNuevo",
    "release_date": "2013-01-08",
    "num_stars": 5
  }
]
  }

This JSON should create the musician and his albums. I've found some examples in the documentation that are useful using "GET" but I would like to do it with "POST".

Abdelilah El Aissaoui
  • 4,204
  • 2
  • 27
  • 47
  • the json you posted needs to be assigned using json.dumps(dict). Did you do that already? I'm sorry for asking this but this information is not available in your question. – minocha May 22 '16 at 16:37
  • I didn't know Django till 2 mins ago. But it seems you have to serialize your Django object. Serialization provides a mechanism for “translating” Django models into other formats. The serialization formats provided are XML, JSON and YAML. Hope [this link](https://docs.djangoproject.com/en/1.9/topics/serialization/) helps. – Ic3fr0g May 22 '16 at 16:40
  • Hmmm... No. I don't understand what do you mean. I don't know this helps or if I should've said this before but I'm posting those JSON using a browser extension to test it. – Abdelilah El Aissaoui May 22 '16 at 16:43
  • Please check [these](http://stackoverflow.com/questions/757022/how-do-you-serialize-a-model-instance-in-django) [answers](http://stackoverflow.com/questions/13031058/how-to-serialize-to-json-a-list-of-model-objects-in-django-python) – Ic3fr0g May 22 '16 at 17:01

0 Answers0