ryanderon
ryanderon

Reputation: 61

Django Rest Framework Relationship

(Question before: Django Rest Framework nested relationship)

I've made serializer like this:

serializers.py

from rest_framework import serializers, fields

from .models import Pegawai,Barang


class BarangSerializer(serializers.ModelSerializer):
    class Meta:
        model = Barang
        fields = (
                'pegawai', 
                'nama_barang',
                'harga_barang',
                )

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        rep['pegawai'] = instance.pegawai.name
        return rep

class PegawaiSerializer(serializers.ModelSerializer):
    barangs = BarangSerializer(read_only=True, many=True)
    class Meta:
        model = Pegawai
        fields = (
                'id',
                'name', 
                'alias',
                'barangs',
                )

Results :

{  
"pegawai": "Ryan",
    "nama_barang": "burjo",
    "harga_barang": "1234"
},

And How to make the result like this in the barang API when posted the data:

{
    "pegawai": {"id" : 1,
        "name" : "Ryan",
        "alias" : "R"}
    "nama_barang": "burjo",
    "harga_barang": "1234"
},

Please help, cheers.

Upvotes: 1

Views: 218

Answers (2)

JPG
JPG

Reputation: 88509

Write extra serializer and wire-up it in to_representation(..) method,

class PegawaiShortSerializer(serializers.ModelSerializer):
    class Meta:
        model = Pegawai
        fields = (
            'id',
            'name',
            'alias',
        )


class BarangSerializer(serializers.ModelSerializer):
    class Meta:
        model = Barang
        fields = (
            'pegawai',
            'nama_barang',
            'harga_barang',
        )

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        rep['pegawai'] = PegawaiShortSerializer(instance.pegawai).data
        return rep

Upvotes: 2

Night Owl
Night Owl

Reputation: 136

Have you try:

rep = super().to_representation(instance)

pegawai_obj = instance.pegawai
pegawai_data = {"id":pegawai_obj.id, "name":pegawai_obj.name, "alias":pegawai_obj.alias}
rep['pegawai'] = pegawai_data

return rep

But I don't think this is the best solution.

Upvotes: 2

Related Questions