Ahmed  Samy
Ahmed Samy

Reputation: 53

Django Rest Framework - Create ForeignKey lookup fields

I'm trying to Create LikeSong which have Related Field with Song model In need to pass slug instead of pk

# models.py 

class LikedSong(AbstractBaseModel):
    MEDIA_TYPE_CHOICES = (
        ('audio', "Audio"),
        ('video', 'Video')
    )
    song = models.ForeignKey(Song, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    media_type = models.CharField(max_length=5,choices=MEDIA_TYPE_CHOICES)

    class Meta:
        verbose_name = _("Liked Song")
        verbose_name_plural = _("Liked Songs")
        unique_together = ['song', 'user', 'media_type']

    def __str__(self):
        return f"{self.song} - {self.user}"models.py

# serializers.py

class LikedSongSerializer(serializers.ModelSerializer):
    song = serializers.SlugRelatedField(
        queryset=Song.objects.all(), slug_field='slug'
    )

    class Meta:
        model = LikedSong
        fields = [
            'song',
            'media_type'
        ]

    def create(self, validated_data):
        liked = LikedSong.objects.get_or_create(user=self.context['request'].user, **validated_data)
        return liked

but i got this error

AttributeError: Got AttributeError when attempting to get a value for field `song` on serializer `LikedSongSerializer`.

The serializer field might be named incorrectly and not match any attribute or key on the tuple instance. Original exception text was: 'tuple' object has no attribute 'song'. [15/Jan/2021 21:24:00] "POST /api/music/like_song/ HTTP/1.1" 500 20927

Upvotes: 0

Views: 553

Answers (1)

Guillaume
Guillaume

Reputation: 2006

Alright the problem is not related to slugrelatedfield.

The problem comes from the fact that in your create method LikedSong.objects.get_or_create(user=self.context['request'].user, **validated_data) returns a tuple (object, created), object being the instance and created a boolean indicating if it was created or if we retrieved it.

liked, _ = LikedSong.objects.get_or_create(user=self.context['request'].user, **validated_data)

That should solve it.

Upvotes: 1

Related Questions