我的模特:
class NewsID(models.Model):
pass
class News(models.Model):
newsId=models.ForeignKey(NewsID,related_name = 'News', on_delete=models.CASCADE)
lang_code=models.CharField(max_length=2)
headline=models.CharField(max_length=100)
class DefaultLanguage(models.Model):
news_id = models.ForeignKey(NewsID,related_name = 'default', on_delete=models.CASCADE)
defaultLanguage_id = models.IntegerField(unique=True)
我的序列化器:
class NewsSerializer(QueryFieldsMixin,serializers.ModelSerializer):
class Meta:
model=News
fields=('lang_code','headline')
class DefaultLanguageSerializer(QueryFieldsMixin,serializers.ModelSerializer):
class Meta:
model = DefaultLanguage
fields = ('news_id ','defaultLanguage_id ')
read_only_fields = ['news_id ','defaultLanguage_id ']
class NewsIDSerializer(QueryFieldsMixin,serializers.ModelSerializer):
News = NewsSerializer(many=True)
default_language = serializers.CharField(max_length=2,write_only=True)
class Meta:
model = NewsID
fields = ('id','News','default_language')
发布后,我希望得到如下响应:
{
"id": 10,
"News": [
{
"lang_code": "en",
"headline": "Breaking news"
}
],
"default_language": "en"
}
现在我的回答如下:
{
"id": 10,
"News": [
{
"lang_code": "en",
"headline": "Breaking news"
}
]
}
现在我的答复是具有news_id和defaultLanguage_id(只读字段),我不希望张贴后具有只读字段的答复。如何使用Django实现此目标?
答案 0 :(得分:1)
更改您的序列化器
class NewsIDSerializer(QueryFieldsMixin,serializers.ModelSerializer):
News = NewsSerializer(many=True)
default = DefaultLanguageSerializer(many=True,read_only=True)
default_language = serializers.CharField(max_length=2,write_only=True)
class Meta:
model = NewsID
fields = ('id','News','default','default_language')
收件人
class NewsIDSerializer(QueryFieldsMixin,serializers.ModelSerializer):
News = NewsSerializer(many=True)
default_language = serializers.CharField(max_length=2)
class Meta:
model = NewsID
fields = ('id','News','default_language')
它将按预期工作。