How to serialize 2 models with custom relationship in django-rest-framework?
<p>I have 2 existing tables in database and i haven't permission to alter them. Show as models below.</p>

<pre><code>class Prenames(models.Model):
    typ = models.DecimalField(max_digits=1, decimal_places=0, db_column='tprpretyp')
    code = models.DecimalField(max_digits=3, decimal_places=0, db_column='tprprecod')
    name = models.CharField(max_length=20, db_column='tprprenam')

class Profiles(models.Model):
    userid = models.CharField(max_length=6, db_column='rmsuserid')
    prename = models.CharField(max_length=4, db_column='rmsprenam', null=True)
    name = models.CharField(max_length=25, db_column='rmsname')
    surname = models.CharField(max_length=25, db_column='rmssurnam')
</code></pre>

<p>If sql i have to </p>

<pre><code>SELECT * FROM Profiles left join Prenames on tprpretyp = int(rmsprenam/1000) and tprprecod = mod(rmsprenam,1000) WHERE trim(rmsuserid) = ?
</code></pre>

<p>Things I've already try:</p>

<pre><code>from rest_framework import serializers
from .models import *

class PrenameSerializer(serializers.ModelSerializer):
    class Meta:
        model = Prenames
        fields = ('type', 'code', 'name')


class ProfileSerializer(serializers.ModelSerializer):
    prenames = PrenameSerializer(read_only=True)

    class Meta:
        model = Profile
        fields = ('userid', 'name', 'surname', 'prenames')
</code></pre>

<p>Things I've got:</p>

<pre><code>{
  "userid": "560174",
  "name": "******",
  "surname": "******"
}
</code></pre>

<p>Things I expected:</p>

<pre><code>{
  "userid": "560174",
  "name": "******",
  "surname": "******"
  "prenames":[
      {
          "type:":10,
          "code": 01,
          "name": "Mr."
      }
  ]
}
</code></pre>

<p>I'm using django-rest-framework 3.2.5 and django 1.6 how do i serialize them?</p>

<p>Thanks @Aison for giving me an inspiration.
This solution is not exactly what I want. But it save my life for now.
From <a href="http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield" rel="nofollow">SerializerMethodField</a>. I decided to modify ProfileSerializer to</p>

<pre><code>class PatientSerializer(serializers.ModelSerializer):
    prenameth = serializers.SerializerMethodField('getprenameth')
    prenameen = serializers.SerializerMethodField('getprenameen')

    def getprenameth(self, obj):
        return obj.prename.name

    def getprenameen(self, obj):
        return obj.prename.en_pre_name

    class Meta:
        model = Patients
        fields = ('userid', 'name', 'surname', 'prenames', 'prenameth', 'prenameen')
</code></pre>

<p>And this what I got from it.</p>

<pre><code>{
  "userid": "560174",
  "name": "******",
  "surname": "******",
  "prenameth": "à¸à¸²à¸¢",
  "prenameen": "Mr."
}
</code></pre>

<p>This is enough for now.</p>

python django django-rest-framework