我正在按照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

最佳答案

发现问题:我跑了

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


在iPython中(通过python manage.py shell_plus)。

我想iPython会以某种方式破坏对象类型。当我在服务器(python manage.py runserver)中运行它时,它的行为正确。

关于python - DRF的嵌套关系:带Tuple的序列化器输出OrderedDict,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30401290/

10-12 18:31