ModelSerializer()由于某种原因不会显示相关模型的__unicode__()
值,而是显示它们的ID - 有没有办法解决这个问题?或者我必须以某种方式明确定义所有相关字段?对于相关模型,我使用了使用HyperlinkedModelSerializer的ModelView。
模型
class ActionItem(CoreBase):
project = models.ForeignKey(Project, null=True, blank=True, related_name='ProjectActionItems')
portfolio = models.ForeignKey(Portfolio, null=True, blank=True, related_name='PortfolioActionItems')
name = models.CharField(max_length=256, null=False)
description = models.TextField(null=True, blank=True)
parent = models.ForeignKey('ActionItem', null=True, blank=True)
priority = models.ForeignKey(DicPriority, default=ActionItem_default_priority)
status = models.ForeignKey(DicActionItemStatus, default=ActionItem_initial_status)
resolution = models.TextField(null=True, blank=True)
assignee = models.ForeignKey(User, null=True, blank=True, related_name='executor')
due_date = models.DateField(null=True, blank=True)
相关模型(优先级):
class DicPriority(DicCoreBase):
name = models.CharField(max_length=64, unique=True, blank=False, null=False)
class Meta:
verbose_name = '[D] Priority'
verbose_name_plural = '[D] Priorities'
它的基类:
class DicCoreBase(CoreBase):
order = models.PositiveSmallIntegerField(default=10, null=False, blank=False)
class Meta:
abstract = True
ordering = ['order']
def __unicode__(self):
if hasattr(self, 'name'):
return self.name
else:
return u'Dic (%s): %s' % (self.__class__.__name__, self.pk)
序列化程序
class ActionItemTextSerializer(serializers.ModelSerializer):
class Meta:
model = ActionItem
fields = ('id', 'created_by', 'created_date', 'project', 'portfolio', 'name', 'description', 'parent', 'priority', 'status')
class ActionItemViewSet(viewsets.ModelViewSet):
queryset = ActionItem.objects.all()
serializer_class = ActionItemTextSerializer
输出:
{
"id": 5,
"created_by": 1,
"created_date": "2015-03-19T18:34:07Z",
"project": 1,
"portfolio": null,
"name": "NEW TEST!!!",
"description": "ACE TEST NEW XOXO",
"parent": null,
"priority": 2,
"status": 2
}
答案 0 :(得分:1)
DRF为相关字段提供密钥,以便在相关对象之间轻松导航。如果要引用相关字段的属性,可以明确定义它:
class ActionItemTextSerializer(serializers.ModelSerializer):
priority_text = serializers.CharField(source='priority')
class Meta:
model = ActionItem
fields = ('id', 'created_by', 'created_date', 'project', 'portfolio', 'name', 'description', 'parent', 'priority_text', 'status')
编辑:
我最初有source='priority__name'
,但凯文指出我使用了错误的语法,它应该是source='priority.name'
,但后来我重新阅读了这个问题,它特别是关于__unicode__
,所以这只是将序列化程序字段定义为CharField的问题,它会自动调用对象上的__unicode__
。所以我们最终得到source='priority'