【发布时间】:2014-01-26 13:24:57
【问题描述】:
我正在仔细阅读http://www.django-rest-framework.org/api-guide/serializers 并尝试实现一个基本的反序列化器。我有点困惑,因为我的实验代码导致随机结果毫无意义。
我有一个简单的 django 模型:
class ArticleType(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=15)
class Article(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=80)
body = models.TextField()
featured = models.BooleanField(default=False)
published = models.BooleanField(default=False)
children = models.ManyToManyField('self')
article_type = models.ForeignKey(ArticleType)
我有一个简单的反序列化器:
class ArticleSerializer(ModelSerializer):
article_type = serializers.CharField(max_length=15)
children = serializers.PrimaryKeyRelatedField(many=True)
class Meta:
model = Article
fields = ('id', 'featured','published','body','title','children','article_type')
在 django shell 中,我运行以下命令:
>>> aData = {'id':3,'featured':True,'published':True, 'body':'This is some body text!', 'title':'This is a title!', 'children':[2,3], 'article_type':'Topic'}
>>> aS = ArticleSerializer(data=aData)
产量:
>>> aS.is_valid()
True
>>> aS.data
{'featured': False, 'published': False, 'body': u'', 'title': u'', 'children': [], 'a_type': u''}
从这里我有几个问题。
为什么要更改数据?
如果数据无效,为什么
.is_valid()方法返回true?文档没有明确说明我将在何处实现从长度为 15 的 CharField 到在我的 article_type 字段中实际返回 ArticleType 实例的转换。
注意:文章表中填充了一些虚拟文章。
【问题讨论】: