Django 序列化父级 class

Django Serialize Parent class

鉴于我有 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,它们来自父 class。

不使用 djangorestframework 因为它不用于任何 REST API,我怎样才能让 GoldMember 的 JSON 表示成为

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

?

在您的 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)

此时您可以打印或return

 serializer.data

其中应包含您需要的 JSON。