2016-08-28 40 views
1

我有2個現有的數據庫表,我沒有權限改變它們。在下面顯示爲模型。如何使用django-rest-framework中的自定義關係序列化2個模型?

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') 

如果SQL我不得不

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

事情我已經嘗試:

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') 

事情我已經有了:

{ 
    "userid": "560174", 
    "name": "******", 
    "surname": "******" 
} 

事情我預計:

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

我使用的是django-rest-framework 3.2.5和django 1.6我如何序列化它們?

+0

'prenames = PrenameSerializer(read_only = True,many = True)'。嘗試使用many = True參數來獲取所有的預設名稱。 –

回答

2

試試這個:

prenames = PrenameSerializer(source="how_you_get_this_field, many=True, read_only=True) 
0

感謝@Aison給我的靈感。 這個解決方案並不完全是我想要的。但它現在拯救了我的生命。 從SerializerMethodField。我決定修改ProfileSerializer爲

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') 

而這就是我從中得到的。

{ 
    "userid": "560174", 
    "name": "******", 
    "surname": "******", 
    "prenameth": "นาย", 
    "prenameen": "Mr." 
} 

這就夠了。

+0

我應該告訴你有關serializermethodfield.Sorry爲我沒有時間來編輯我的答案(我現在在婚禮上)無論如何,很高興知道你弄明白了。 – Windsooon

相關問題