0

class ScreenCategorySerializer(serializers.ModelSerializer):
    screen = ScreenListingField(many=True, read_only=True)

    class Meta:
        model = ScreenCategory
        fields = ['id', 'title', 'screen', 'active', 'position']

class ScreenListingField(serializers.RelatedField):
    def to_representation(self, value):
        res = {}
        # Need get ScreenCategory id here
        res['id'] = value.id
        res['title'] = value.title
        res['layout'] = value.layout
        res['project'] = value.project.id
        res['last_change'] = value.last_change
        res['width'] = value.width
        res['height'] = value.height
        res['background_color'] = value.background_color
        if value.constant_color is None:
            res['constant_color'] = None
        else:
            res['constant_color'] = value.constant_color.id
        res['styles'] = value.styles
        res['base'] = value.base
        return res

I have the following serializer, inside the ScreenListingField I would like to get the id of the ScreenCategory. How can I get it?

  • Does this answer your question? [How to access forgin key value in react from django api](https://stackoverflow.com/questions/67523331/how-to-access-forgin-key-value-in-react-from-django-api) – Ankit Tiwari Aug 22 '21 at 08:49
  • 1
    Maybe get it by overriding `to_representation` of `ScreenCategorySerializer` and inject it on the representation of `screen` field? But just curious why you need it? You already have the id from the parent? – Brian Destura Aug 22 '21 at 09:48
  • @bdbd Based on the id, additional data will need to be retrieved and displayed in screen – Kabiljan Tanaguzov Aug 22 '21 at 10:09
  • 1
    Hmm I see. Maybe use a serializer method field in `ScreenCategorySerializer`? – Brian Destura Aug 22 '21 at 10:10
  • @bdbd Thanks for the advice. I used it and implemented what I needed. – Kabiljan Tanaguzov Aug 22 '21 at 10:26

0 Answers0