V
V
Viktor Usachov2016-03-30 17:36:23
Python
Viktor Usachov, 2016-03-30 17:36:23

How to implement such logic on tastypie?

I'm trying to implement a Python / Django and Tastypie REST API , a regular check is taken as an example.
Given:
A receipt has:
- receipt number (unique value),
- date of receipt creation,
- date of last modification of the receipt (filled in by the application),
- total cost of goods,
- discount (filled in by the application),
- amount payable (filled in by the application),
- status (by default "Processed").
Upon POST request to the collection, the web service must:
- create a new receipt if the receipt number is missing in the sent data; otherwise, try to update an already existing check whose number matches the one sent
- in case of creating a new check, create a check number in the format "RCPT-<unique number>",
- calculate the amount of the discount as 3% of the total cost of the goods, and fill in the "discount" field with the received value,
- calculate the amount payable as the difference between the values ​​of the total cost of the goods and the discount; fill in the "Amount payable" field with the resulting value
- in case of creating a new receipt, and if the date/time of receipt creation is missing in the sent data, fill in the "date of receipt creation" field with the current date/time; if there is a check creation date in the sent data, save the sent date,
- in case of updating an existing check, keep the original check creation date regardless of the data sent,
- fill in the "check last modification date" field with the current date/time, ignoring any data sent,
- fill in the status field with the default value "Processed".
A web service on a GET request to a collection should return all checks with the "Processed" status. Checks with other statuses should be hidden.
The web service, upon request DELETE to a collection instance, should change the status of the selected receipt to the status "Canceled".
All other requests should be ignored by the web service.
Wrote:
retail/models.py:

import uuid
from django.db import models
from django.utils import timezone

class Receipt(models.Model):
    ''' Retail receipt '''
    number = models.CharField(max_length=20, unique=True, editable=False)
    full_price = models.FloatField()
    discount = models.FloatField()
    final_amount = models.FloatField()
    status = models.CharField(max_length=20, default='Обработан')

    created = models.DateTimeField()  # editable=True
    modified = models.DateTimeField()

    def __init__(self, *args, **kwargs):
        super(Receipt, self).__init__(*args, **kwargs)
        # "RCPT-<уникальный номер>"
        self.number = 'RCPT-' + uuid.uuid4().hex
                
    def save(self, *args, **kwargs):
        ''' On save, update timestamps '''
        self.modified = timezone.now()
        if not self.id:
            self.created = self.modified
        return super(Receipt, self).save(*args, **kwargs)

retail/api.py:
from tastypie.resources import ModelResource
from tastypie.authorization import Authorization
from retail.models import Receipt

class ReceiptResource(ModelResource):
    class Meta:
        queryset = Receipt.objects.all()
        list_allowed_methods = ['get', 'post', 'delete']
        resource_name = 'receipt'
        authorization = Authorization()
#        filtering = {
#            'status': ['Обработан'],
#        }

        def get_object_list(self, request):
            # .filter(status='Обработан') -  это ничего не дало
            return super(ReceiptResource, self).get_object_list(request).filter(status='Обработан')

myapp/urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from retail.api import ReceiptResource

receipt_resource = ReceiptResource()

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api/', include(receipt_resource.urls)),
]

Working with dates seems to meet the requirements, the number too, but filtering by status, performing any logic on POST / GET / DELETE requests - how to do this?
Please tell me what I need in Tastypie to implement this. The third day I search in the documentation "that, without knowing that".

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question