Django Serialize Parent类

时间:2016-06-20 02:17:21

标签: django django-serializer

鉴于我有2个型号:

class Member(models.Model):
    name = models.CharField()
    userid = models.CharField()

class GoldMember(Member):
    parent_model = models.OneToOneField(Member, parent_link=True)
    date_start = models.DateField()

serializers.serialize("json", gold_member, fields=['name', 'userid', 'date_start']
        , use_natural_foreign_keys=True)

当我打印JSON时,我只看到date_start字段。但是,我希望nameuserid来自父类。

不使用djangorestframework,因为这不用于任何REST API,如何将GoldMember的JSON表示形式设为

{'date_start' = '2016-01-01', 'name' = 'John Doe', 'userid' = 'john.doe'}

1 个答案:

答案 0 :(得分:0)

你的serializers.py中的

包括:

from rest_framework import serializers

from models import Member
from models import GoldMember


class MemberSerializer(serializers.ModelSerializer):
    class Meta:
        model = Member
        fields = ('id','name','userid')


class GoldMemberSerializer(serializers.ModelSerializer):
    parent_model = MemberSerializer(many=False,read_only=True)

    class Meta:
        model = GoldMember
        fields =  ('id','parent_model','date_start')

然后你的意见中有些人:

 serializer = GoldMemberSerializer(gold_member,many=False)

此时您可以打印或返回

 serializer.data

应该包含您需要的JSON。