DRF的嵌套关系:序列化器输出带有元组的OrderedDict

时间:2015-05-22 16:06:05

标签: python django

我跟随this guide序列化一个对象及其嵌套关系:

class EmployeeWorkShift(models.Model):
    employee = models.ForeignKey(CompanyEmployees, unique=True)
    work_shift = models.ForeignKey(WorkShift, unique=True, related_name='employee_work_shifts')

class WorkShift(models.Model):
    workers = models.ManyToManyField('CompanyEmployees', through='EmployeeWorkShift')
    is_active = models.BooleanField(default=True)

class EmployeeWorkShiftSerializer(serializers.ModelSerializer):
    class Meta:
        model = EmployeeWorkShift
        fields = ('id')

class WorkShiftSerializer(serializers.ModelSerializer):
    employee_work_shifts = EmployeeWorkShiftSerializer(many=True, read_only=True)
    class Meta:
        model = WorkShift
        fields = ('id', 'employee_work_shifts')
    depth = 1

但是,当我这样做时

WorkShiftSerializer(WorkShift.objects.get(pk=1)).data

我明白了:

{'employee_work_shifts': [OrderedDict([('id', 13)]), OrderedDict([('id', 14)])], 'id': 1}

似乎DRF将 employee_work_shifts 视为OrderedDict的列表......

我是否错过任何明显的事情?

requirements.txt:

djangorestframework==3.1.2
Django==1.7.8

1 个答案:

答案 0 :(得分:1)

发现问题:我跑了

WorkShiftSerializer(WorkShift.objects.get(pk=1)).data
iPython中的

(通过python manage.py shell_plus)。

我想不知怎的,iPython搞砸了对象类型。当我在服务器(python manage.py runserver)中运行它时,它的行为正确。