vendredi 10 juin 2016

store pk from detail route in the serializer [django REST API]


I asked this question before but with less clarity

How to save the id inside the RelatedFiled of the ForeignKey ?

I am testing an application on django, I have two models:

class Album(models.Model):
    album_id = models.IntegerField()
    artist = models.CharField(max_length=260)
    album_name = models.CharField(max_length=260)


class Song(models.Model):
    album = models.ForeignKey(Album, related_name='song', blank=True, null=True)    #foreign key
    song_name = models.CharField(max_length=260)

with Song containing a foreign key to Album

My question is how do I store automatically the pk or id of album inside that foreign key ?

I have set up a detail_route , and when I print album_id I get the correct one that I am trying to access in the url

for example: album/101/song will print album_id as 101. But in my serializer it is not saving the RelatedField as 101. How do I fix this ?

    @detail_route(methods=['post', 'get'], serializer_class=SongSerialiser)
    def get_so(self, request, album_id=None):
        serializer = self.get_serializer(data=request.data, context={"album_id": album_id })
        if serializer.is_valid():
            print album_id # this works !
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response({"detail": serializer.errors,
                             "status_code": status.HTTP_400_BAD_REQUEST})

Serializer:

class SongSerialiser(serializers.Serializer):
    album = serializers.RelatedField(many=True)
    song_name = serializers.CharField(required=False)

    def create(self, validated_data):
        album_id = self.context.get("album_id")
        print album_id   # I expect this to print 101 or the related id
        instance = Song.objects.create(**validated_data)
        instance.save()
        return instance

Aucun commentaire:

Enregistrer un commentaire