我有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我如何序列化它們?
'prenames = PrenameSerializer(read_only = True,many = True)'。嘗試使用many = True參數來獲取所有的預設名稱。 –