我有两个模型如下:
# parent model
class Klass(models.Model):
title = models.CharField(max_length=50)
description = models.CharField(max_length=500)
# child model
class KlassSettings(models.Model):
klass = models.OneToOneField(Klass, related_name='klass_settings', on_delete=models.CASCADE)
private = models.BooleanField(default=True, choices=(
(True, 'private'),
(False, 'public'),
))
verify_required = models.BooleanField(default=True, choices=(
(True, 'required'),
(False, 'not required'),
))
我想用Django Rest Framework创建Klass
。我使用下面的序列化器:
class KlassSerializer(ModelSerializer):
url = HyperlinkedIdentityField(view_name='mainp-api:detail', lookup_field='pk')
class Meta:
model = Klass
fields = ('url', 'id', 'title', 'description')
我的问题是:如何获取KlassSettings
模型(2个BooelanFields)的数据并保存?
答案 0 :(得分:0)
暂且不谈模型设计的任何问题(私有和验证只是Klass中的字段吗?),我相信你要找的是serialzing a reverse relationship。您的最终解决方案看起来与您的解决方案类似,但会在KlassSerializer中包含klass_settings
字段并创建KlassSettingsSerializer类。