Home > Back-end >  Django Rest Framework (DRF) how to get value of GenericRelation field?
Django Rest Framework (DRF) how to get value of GenericRelation field?

Time:10-08

at my models.py I have a "Movies" model with the following field setup:

video_stream_relation = GenericRelation(VideoStreamInfo, related_query_name='video_stream_relation')

This GenericRelation field points to the following model class:

class VideoStreamInfo(models.Model):
    objects = RandomManager()
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    content_type = models.ForeignKey(ContentType, limit_choices_to=referential_stream_models, on_delete=models.CASCADE, verbose_name=_("Content Type"))
    object_id = models.CharField(max_length=36, verbose_name=_("Object ID"))
    content_object = GenericForeignKey('content_type', 'object_id')
    index = models.IntegerField(verbose_name=_("Stream Index"), blank=False)
    bit_rate = models.IntegerField(verbose_name=_("Bitrate (bps)"), blank=True, null=True, editable=False)
    codec_name = models.CharField(verbose_name=_("Codec Name"), blank=True, null=True, editable=False, max_length=255)
    width = models.IntegerField(verbose_name=_("Width"), blank=True, null=True, editable=False)
    height = models.IntegerField(verbose_name=_("Height"), blank=True, null=True, editable=False)
    date_added = models.DateTimeField(auto_now_add=True, verbose_name=_("Date Added"))

Now the Question is how can I get video_stream_relation.codec_name value in a ModelSerializer like this:

class MovieSerializer(serializers.ModelSerializer):
    id = serializers.PrimaryKeyRelatedField(queryset=Movies.objects.all())
    class Meta:
        model = Movies
        fields = ('id',
                  ...)

I want to be able to display the codec_name as a API JsonResponse.

If needed, this is how my API view currently looks like:

@api_view(['GET',])
@authentication_classes([JSONWebTokenAuthentication])
@permission_classes([AllowAny])
def movies(request):
    if request.method == 'GET':
        obj = Movies.objects.all()
        serializer = MovieSerializer(obj, many=True)
        return JsonResponse(serializer.data, safe=False)

If I try to add the video_stream_relation field to my MovieSerializer I get back the following error:

TypeError: Object of type GenericRelatedObjectManager is not JSON serializable

Thanks in advance.

CodePudding user response:

You can create a model serializer for VideoStreamInfo like this and use it in MovieSerializer as a related manager like this:

from rest_framework import serializers


class VideoStreamInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = VideoStreamInfo
        fields = ('codec_name', )


class MovieSerializer(serializers.ModelSerializer):
    video_stream_relation = VideoStreamInfoSerializer(many=True, read_only=True)
    id = serializers.PrimaryKeyRelatedField(queryset=Movies.objects.all())

    class Meta:
        model = Movies
        fields = ('id',
                  'video_stream_relation',
                  ...
                  )
  • Related