python - Django rest update object from other model -


i using django 1.7 rest framework,. want update cart instance , create new instance of order.

#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 deleted , create order instance     # request can come 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) 

i feel not best way write logic. because following situation can occur, cart updated , order instance not created. don't know how know cart not converted order. there better way achieve this?

you can manually create order , update cart after that, this:

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) 

Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -