Django从其他模型休息更新对象

时间:2015-04-23 04:20:43

标签: python django rest

我正在使用带有REST framework,的Django 1.7。我想更新购物车实例,然后创建新的订单实例。

#models.py

class Cart(models.Model):
  to_be_deleted = models.BooleanField(default=False)
  ...

class Order(models.Model):
  ...

#views.py
class OrderBuyList(generics.ListCreateAPIView):
    serializer_class = OrderBuySerializer

def create(self, request, *args, **kwargs):
    data = request.data
    # First mark cart instance to be deleted and then create an order instance
    # Request can come from cart.
    cart = Cart.objects.filter(id=data['id'],user_id=data['user_id'])
    if cart:
        cart[0].to_be_deleted = True
        cart[0].save()
    return generics.ListCreateAPIView.create(self, request, *args, **kwargs)

我觉得这不是编写这种逻辑的最佳方式。由于可能发生以下情况,因此更新了购物车并且未创建订单实例。然后,我不知道如何知道哪个购物车not已转换为订单。 有没有更好的方法来实现这个目标?

1 个答案:

答案 0 :(得分:0)

您可以手动创建订单并在此之后更新购物车,如下所示:

def create(self, request, *args, **kwargs):
    data = request.data
    cart = Cart.objects.get(id=data['id'],user_id=data['user_id'])
    serializer = self.get_serializer(data=data)
    serializer.is_valid(raise_exception=True)
    order = Order.objects.create(**serializer.validated_data)
    cart.to_be_deleted = True
    cart.save()
    headers = self.get_success_headers(serializer.data)
    return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)