With the model below, I want to create a function that returns the details of daily sales for the current month. The details will be the total number of sales for each day and sum of sales for each day. I've tried using ExtractDay and annotate but I'm not getting the desired output or maybe I'm not doing it right
class Stamping(models.Model):
created = models.DateTimeField(auto_now_add=True)
class Meta:
abstract = True
class Order(Stamping):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=300, unique=True)
price = models.FloatField()
quantity = models.IntegerField()
In my location, the date is Tuesday, 2 November 2021. So the output should look like this
<QuerySet [{'day': 1, 'count': 9, 'total': 100.0}, {'day': 2, 'count': 7, 'total': 80.0}]>
And after today, I should also {'day': 3, 'count': 15, 'total': 200.0}
and it keeps going till the end of the month then I'll start getting only the data for that month too
CodePudding user response:
Connect the order model with the stamping one
Change stamping created field from DateTimr to DateFirld Use celery to create a new stamping object at 00:00 of each new day with the created field equals today's date So when creating the order object just get the stamping object with today's date And whenever you want just make an api to return the related orders to today's stamping object using the related name specified in the foreign key field connecting order to stamping
CodePudding user response:
bellow code is creating the query set by taking attribute which you want by lookups it will give the separate out put of day ,count and total value after getting that query_set store create or store them as you want
you can add them in one model and can call them by filter from filter
views.py
from django.db.models import Q
def get_queryset(self):
qlookup1 = Q(day=self.request.value)
qlookup2 = Q(count=self.request.value)
qlookup3 = Q(total=self.request.value)
queryset = model.objects.filter(qlookup1 | qlookup2 | qlookup3).distinct()
active = self.request.query_params.get('active', True)
try:
queryset = queryset.filter(is_active=active)
return queryset
except Exception as error:
return queryset.none()
if you want flat formate queryset then you can use drf_multiple_model