鉴于我有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
字段。但是,我希望name
和userid
来自父类。
不使用djangorestframework
,因为这不用于任何REST API,如何将GoldMember
的JSON表示形式设为
{'date_start' = '2016-01-01', 'name' = 'John Doe', 'userid' = 'john.doe'}
答案 0 :(得分:0)
包括:
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。