python 3.x - In django-rest-framework, serialize model from a different class -
i writing point-of-sale (pos) system in django. have basic functionality, , before go adding more complexity trying clean code.
as part of effort moving ajax calls part of api django-rest-framework.
in models have transaction represents items customer has purchased. each individual purchase in transaction lineitem. in transactionviewset api class have function named ring_plu. takes in upc , quantity, adds item lineitem upc, , want return new lineitem. code looks this.
transactionviewset @detail_route( methods=['post'], renderer_classes=[renderers.statichtmlrenderer] ) def ring_upc(self, request, *args, **kwargs): upc = request.post['upc'] quantity = request.post['quantity'] if len(upc) != 12: return response('invalid upc', status=status.http_400_bad_request) grocery = get_object_or_404(grocery, upc=upc) transaction = self.get_object() line_item = transaction.create_line_item(grocery, quantity) serializer = lineitemserializer(line_item, context={'request':request}) return response(serializer.data)
i calling /api/transactions/10/ring_upc/ post body {'upc':'071990095314','quantity':1}
, requesting application/json response. this.
urlcodequantityscaledescriptionpricestatustransactionitem
i have played around few different options serializers, cannot seem serializer work correctly.
here other parts of code may useful.
serializers.py
class lineitemserializer(serializers.hyperlinkedmodelserializer): class meta: model = lineitem
models.py
class lineitem(models.model): transaction = models.foreignkey(transaction) code = models.charfield(max_length=30) quantity = models.decimalfield(max_digits=15, decimal_places=0) scale = models.decimalfield(max_digits=19, decimal_places=4, null=true) description = models.charfield(max_length=100) price = models.decimalfield(max_digits=17, decimal_places=2) item = models.foreignkey('inventory.item') status = models.charfield(max_length=8, default='active') def __unicode__(self): return str(self.scale) + ' x ' + self.description + ' ' +\ self.description def total(self): return self.price * self.quantity def cancel(self): self.status = 'inactive'
the problem in renderers.statichtmlrenderer
.
from documentation renderer is:
a simple renderer returns pre-rendered html. unlike other renderers, data passed response object should string representing content returned.
renderer expects plain text in response data. receives dict
, transforms string iterating on it.
you can remove renderer_classes=[renderers.statichtmlrenderer]
@detail_route
arguments.
Comments
Post a Comment