Post Django Rest Framework 中当前用户的对象列表

Post a list of objects with the current user in Django Rest Framework

花了我一段时间才完成,如何 post 一个 list/array 满 JSON 个对象与当前用户,很多混合答案,但这个对我有用, 我希望这对某人有所帮助,继续学习,继续玩得开心。

下一步是设置 get_queryset 以获取每个用户的订单

Post 对象列表以table顺序相同的顺序(勾选fk_order OrderProductsSerializer 中的变量)。

有两个多对多 tables,OrderModel y ProductModel,所以为了添加更多字段,我创建了 OrderProductsModel table 是的,这就是我处理这种情况的方式,寻找了解如果向更有经验的专业人士学习和成长是好是坏,谢谢大家,干杯

接受改进和避免共享错误或不良做法的建议,我将编辑答案。

############################# models.py######################################

class OrderProductsModel(models.Model):
        quantity_order_product = models.IntegerField(default=0, null=True, blank=True)
        price_order_product = models.FloatField(default=0,null=True, blank=True)
        fk_product = models.ForeignKey(ProductModel, null=True, blank=True, on_delete=models.SET_NULL)
        fk_user = models.ForeignKey(CustomUser, null=True, blank=True, on_delete=models.SET_NULL)
        ...
        ...
        ... more fields

############################# views.py######################################

class PostOrderProduct(mixins.CreateModelMixin,
                        generics.GenericAPIView):
    
    serializer_class = OrderProductsSerializer
    
    def get_queryset(self):
        return OrderProductsModel.objects.all()

    def post(self, request, *args, **kwargs):
        items = request.data
        if isinstance(items, list):
            serializer = self.serializer_class( instance='',
                                                data=items, 
                                                many=True, 
                                                context = {
                                                            "request": self.request,
                                                            }
                                                            )
            if serializer.is_valid(raise_exception=True):
                serializer.save()
                return Response(serializer.data, status=status.HTTP_200_OK)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        
        elif isinstance(items, dict):
            return self.create(request, *args, **kwargs)
   

############################# serializers.py ######################################
class OrderProductsListSerializer(serializers.ListSerializer):

    def update(self, instance, validated_data):
        # Perform creations and updates.
        ret = []
        for data in validated_data:
            if data.get('id') not in {'', None}:
                OrderProductsModel.objects.filter(id=data['id']).update(**data)
                ret.append(data)
            else:
                ret.append(OrderProductsModel.objects.create(**data))
        return ret


class OrderProductsSerializer(serializers.ModelSerializer):
    fk_user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    fk_order = serializers.HiddenField(default=OrderModel.objects.create())
    
    class Meta:
        model = OrderProductsModel
        list_serializer_class = OrderProductsListSerializer
        fields = ['fk_user', 'quantity_order_product', 'price_order_product', 'fk_product']