Django rest框架:嵌套的序列化程序是否是更新的正确方法?

时间:2019-04-16 15:06:53

标签: django django-models django-rest-framework django-forms django-views

我对django和django rest框架还很陌生...如果我问一个愚蠢的问题,我仍然在学习,请原谅...对不起...

说!

以下是我正在研究的模型:

class Targets(models.Model):
    first_name = models.TextField()
    last_name = models.TextField()
    email = models.TextField()
    position = models.TextField()

class Groups(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_id')
    name = models.TextField(unique=True, null=False)
    modified_date = models.DateTimeField(auto_now_add=True)
    targets = models.ManyToManyField(Targets)

组扩展了核心用户模型 因此,一个用户可以有多个组。 群组有多个目标 目标可以是多个组的一部分

以下是端点:

urlpatterns = [
    path('groups/', GroupsAPIView.as_view()),
    path('groups/<int:pk>/', GroupsIDAPIView.as_view())
]

以下是序列化器:

class GroupsIDSerializer(serializers.ModelSerializer):
    targets = TargetsSerializer(many=True)
    class Meta:
        model = Groups
        fields = ('id', 'name', 'modified_date', 'user_id', 'targets', )

    def update(self, instance, validated_data):
        targets = validated_data.pop('targets')
        group = Groups.objects.filter(id=instance.id).first()
        Groups.objects.filter(id=instance.id).update(**validated_data)
        group.targets.clear()
        for target in targets:
            obj, created = Targets.objects.get_or_create(**target)
            group.targets.add(obj)
        return Groups.objects.filter(id=instance.id)

class TargetsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Targets
        fields = ('id', 'first_name', 'last_name', 'email', 'position', )

以下是视图:

class GroupsIDAPIView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Groups.objects.all()
    serializer_class = groups.GroupsIDSerializer
    permission_classes = (permissions.IsAuthenticated,)

    def get_queryset(self):
        queryset = super(GroupsIDAPIView, self).get_queryset()
        queryset = queryset.filter(user=self.request.user)
        return queryset

这是我要构建的API的行为:

PUT (url/groups/<int:pk>): Modify the specific group with all the targets for the connected user

{
    "name":"changed",
    "targets":[
        {
            "first_name": "changed",
            "last_name": "a",
            "email": "a@a.fr",
            "position":"a"
        }
    ]
}

Response =>
{
    "id": 1,
    "name": "changed",
    "modified_date": "new date",
    "user_id": 1,
    "targets": [
        {
            "id": 1,
            "first_name": "changed",
            "last_name": "a",
            "email": "a@a.fr",
            "position": "a"
        }
    ]
}

我所说的一切...这是问题所在

1)PUT (url/groups/<int:pk>)仍然存在问题。哪个仍然无法正常工作...不知道如何仅更新该组的目标。 我收到以下错误:Got AttributeError when attempting to get a value for field 'name' on serializer 'GroupsIDSerializer'.

2)处理错误和回滚的正确方法?我认为解决方案是使用原子事务?但是我不确定吗?如果您愿意举一个例子,我将不胜感激...

3)我不确定我所做的事情是否真的正确……我愿意就所有这些获得任何反馈。由于该项目的其余部分非常相似。

4)再次感谢您!

此致

0 个答案:

没有答案