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".

4
  • 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. Commented May 22, 2016 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 helps. Commented May 22, 2016 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. Commented May 22, 2016 at 16:43
  • Please check these answers Commented May 22, 2016 at 17:01

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.