Django RF可写嵌套序列化器

时间:2017-10-04 13:02:55

标签: python django django-rest-framework

我正在尝试在DRF3中创建一个可写的嵌套序列化程序。 我有一个模特音乐会,有一个m2m的场地和技术人员'到我的用户模型。 我已经在其视图中成功添加了连接到Concert实例的用户列表。现在我希望能够将技术人员/用户添加到Concert模型中。

到目前为止,这是我的序列化程序:

class ConcertListSerializer(serializers.ModelSerializer):
    technicians = UserDetailSerializer(
            many=True,
            read_only=True
        )

    class Meta:
        model = models.Concert
        fields = [
            'name',
            'date',
            'technicians',
            'id',
        ]

    def create(self, validated_data):
        # list of pk's
        technicians_data = validated_data.pop('technicians')
        concert = Concert.object.create(**validated_data)

        for tech in technicians_data:
            tech, created = User.objects.get(id = tech) 
            concert.technicians.add({
                    "name": str(tech.name),
                    "email": str(tech.email),
                    "is_staff": tech.is_staff,
                    "is_admin": tech.is_admin,
                    "is_superuser": tech.is_superuser,
                    "groups": tech.groups,
                    "id": tech.id
                })
        return concert

我希望能够添加我想要添加的技术人员的pk / id列表。例如:

"technicians": [1,2,3]

将用户1,2,3添加到Concert的技术人员领域。

每当我这样做时,我得到的KeyError只是说技术人员'并指我的create()函数中的第一行......

我在字典中添加的字段是用户模型的所有字段。这是我执行GET请求时显示的格式。

这是Concert-model:

class Concert(models.Model):
    name = models.CharField(max_length=255)
    date = models.DateTimeField(default =
                                datetime.now(pytz.timezone('Europe/Oslo'))
                                + timedelta(days=30)
                            )
    technicians = models.ManyToManyField(User)  # relation to user model

编辑: 这是GET请求对预制示例音乐会的响应:

{
    "name": "Concert-name",
    "date": "2017-10-28T12:11:26.180000Z",
    "technicians": [
        {
            "name": "",
            "email": "test2@test.com",
            "is_staff": true,
            "is_admin": true,
            "is_superuser": false,
            "groups": [
                5
            ],
            "id": 2
        },
        {
            "name": "",
            "email": "test3@test.com",
            "is_staff": true,
            "is_admin": true,
            "is_superuser": false,
            "groups": [
                5
            ],
            "id": 3
        }
    ],
    "id": 1
}

1 个答案:

答案 0 :(得分:1)

您应该从上下文请求中获取数据,因为您提交的内容是只读的validated_data

def create(self, validated_data):
    # list of pk's
    # instaed of technicians_data = validated_data.pop('technicians')
    # use next two lines
    request = self.context.get('request')
    technicians_data = request.data.get('technicians')

    concert = Concert.object.create(**validated_data)

    # Added technicians
    for tech in technicians_data:
        user = User.objects.get(id=tech) 
        concert.technicians.add(user)

    return concert