I got the from date and to date from the user. I want to return the Sold Product's price and its count in the basis of Daily sold order. how? - django

models.Order.objects.filter(purchasedate__range=[from_date, to_date])
today_total = 0
quant = 0
for values in daterangeorder:
today_total += values.price
quant += values.quantity
return response.Response({
"from_date": from_date,
"to_date": to_date,
"Amount Sold": str(today_total),
"Count": str(quant)
})
This is the output:
{
"from_date": "2021-11-19",
"to_date": "2021-11-23",
"Amount Sold": "27000",
"Count": "9"
}
I want like this (day by day sold products count):-
{
date: “'2021-10-20”,
count: 20,
total_price_sold: 5000.00
},
{
date: “'2021-10-21”,
count: 4,
total_price_sold: 300.00
}

Instead of solving your problem with Python code, you can let the database handle it for you using aggregation, see the docs: https://docs.djangoproject.com/en/3.2/topics/db/aggregation/#values
from django.db.models import Sum
result = models.Order.objects.values('purchasedate')
.order_by('purchasedate')
.annotate(total_price_sold=Sum('price'), count=Sum('quantity'))
return response.Response(result)

Related

Flutter Filter List base on Month

How I can categorise list based on Month
let say I have example list like below :
Record(
id: '01',
nameFood: 'ravioli',
date : 2021/may/14,
price: 20
),
Record(
id: '02',
nameFood: 'cheese garlic',
date : 2021/june/02,
price: 30,
),
Record(
id: '03',
nameFood: 'steak',
date : 2021/march/21
price 25,
),
I want to Categorize it to like this
June(
nameFood: steak,
total price: 240,
),
and etc
the problem is I dnt know how to filter each List(month) because each month have different length of days like 30,31 and 28
If you store your dates as a DateTime, you can try using the month number. I'm going on a limb here, assuming you have a List of objects of type Record, where Record is.
class Record {
Record(
this.id,
this.price,
this.date,
this.nameFood,
);
final String id;
final double price;
final DateTime date;
final String nameFood;
}
You can loop through your list and do whatever it is you want to do with it, like so.
for (final record in _listOfRecords) {
final _monthOfRecord = record.date.month; // Gives the month number. January = 1, April = 4, etc.
// Do other stuff, based on the current monthNumber
switch (_monthOfRecord) {
case 1:
// Do something
break;
....
default:
break;
}
}

Replacing blank with zero for a mesure gives som unexpected extra rows

I have a little puzzle that annoys me in PowerBI/DAX. I'm not looking for workarounds - I am looking for an explanation of what is going on.
I've created some sample data to reconstruct the problem.
Here are my two sample tables written in DAX:
Events =
DATATABLE (
"Course", STRING,
"WeekNo", INTEGER,
"Name", STRING,
"Status", STRING,
{
{ "Python", 1, "Joe", "OnSite" },
{ "Python", 1, "Donald", "Video" },
{ "DAX", 2, "Joe", "OnSite" },
{ "DAX", 2, "Hillary", "Video" },
{ "DAX", 3, "Joe", "OnSite" },
{ "DAX", 3, "Hillary", "OnSite" },
{ "DAX", 3, "Donald", "OnSite" }
}
)
WeekNumbers =
DATATABLE ( "WeekNumber", INTEGER, { { 1 }, { 2 }, { 3 }, { 4 } } )
I have a table with events and another table with all weeknumbers and there is a (m:1) relation between them on the weekNo/weeknumber (I've given them different names to easily distinguish them in this example). I have a slicer in PowerBI on the weeknumber. And I have a table which shows aggregation and counts the participants based on the status with the following measures:
#OnSite = COUNTROWS(FILTER(events,Events[Status]="OnSite"))
#Video = COUNTROWS(FILTER(events,Events[Status]="Video"))
I visualize the two measures in a table together with the Course and the weekNo. With the slicer on weekNumber 3 there are nobody with status video so #video is blank. See screenshot.
Then I decided to create a new measure which should show a 0 instead of blank for the #video:
#VideoWithZero = VAR counter=COUNTROWS(FILTER(events,Events[Status]="Video"))
RETURN IF(ISBLANK(counter),0,counter)
I add the #VideoWithZero to the table and get a lot of extra rows in the table for the other weekNo's:
So my question is - Why do I get the extra rows for week 1 and 2 in the table? I would expect my filter on WeekNumber to filter them out.
The filter is being applied to the context of the query executed, and then the measures are calculated. Now the issue is that one of your measures is always returning a value (0), so regardless of your context it will always show a result, thus making it seem that it is ignoring the filter.
One way I tend to get implement this is by providing some additional context to when I might want to show 0 instead of blank. In your case it would be when one of the counts is not blank:
#OnSite =
VAR video = COUNTROWS(FILTER(events,Events[Status]="Video"))
VAR onsite = COUNTROWS(FILTER(events,Events[Status]="OnSite"))
RETURN IF(ISBLANK(video), onsite, onsite + 0) //+0 will force it not to be blank
#Video =
VAR video = COUNTROWS(FILTER(events,Events[Status]="Video"))
VAR onsite = COUNTROWS(FILTER(events,Events[Status]="OnSite"))
RETURN IF(ISBLANK(onsite), video, video + 0)
So on the OnSite measure it will check if there are Videos and if so, it adds +0 to the result of the OnSite count to force it not to be blank (and vice versa)
One other way could be to count total rows and subtract the ones different to the status you need:
#OnSite =
VAR total= COUNTROWS(Events[Status])
VAR notOnsite = COUNTROWS(FILTER(events,Events[Status]<>"OnSite"))
RETURN total - notOnsite
#Video =
VAR total= COUNTROWS(Events[Status])
VAR notVideo= COUNTROWS(FILTER(events,Events[Status]<>"Video"))
RETURN total - notVideo

How to display all dates for multiple model annotations in django

So I'm working on a website, and I want to have some kind of a summary page to display the data that I have. Let's say I have these models:
class IceCream(TimeStampedModel):
name = models.CharField()
color = models.CharField()
class Cupcake(TimeStampedModel):
name = models.CharField()
icing = models.CharField()
So on this page, users will be able to input a date range for the summary. I'm using DRF to serialize the data and to display them on the view actions. After I receive the filter dates, I will filter out the IceCream objects and Cupcake objects using the created field from TimeStampedModel.
#action(detail=False, methods=['get'])
def dessert_summary(self, request, **kwargs):
start_date = self.request.query_params.get('start_date')
end_date = self.request.query_params.get('end_date')
cupcakes = Cupcake.objects.filter(created__date__range=[start_date, end_date])
ice_creams = IceCream.objects.filter(created__date__range=[start_date, end_date])
After filtering, I want to count the total cupcakes and the total ice creams that is created within that period of time. But I also want to group them by the dates, and display the total count for both ice creams and cupcakes based on that date. So I tried to annotate the querysets like this:
cupcakes = cupcakes.annotate(date=TruncDate('created'))
cupcakes = cupcakes.values('date')
cupcakes = cupcakes.annotate(total_cupcakes=Count('id'))
ice_creams = ice_creams.annotate(date=TruncDate('created'))
ice_creams = ice_creams.values('date')
ice_creams = ice_creams.annotate(total_ice_creams=Count('id'))
So I want the result to be something like this:
{
'summary': [{
'date': "2020-09-24",
'total_ice_creams': 10,
'total_cupcakes': 7,
'total_dessert': 17
}, {
'date': "2020-09-25',
'total_ice_creams': 6,
'total_cupcakes': 5,
'total_dessert': 11
}]
}
But right now this is what I am getting:
{
'summary': [{
'cupcakes': [{
'date': "2020-09-24",
'total_cupcakes': 10,
}, {
'date': "2020-09-25",
'total_cupcakes': 5,
}],
'ice_creams': [{
'date': "2020-09-24",
'total_ice_creams': 7,
}, {
'date': "2020-09-27",
'total_ice_creams': 6,
}]
}]
}
What I want to ask is how do I get all the dates of both querysets, sum the ice creams and cupcakes, and return the data like the expected result? Thanks in advance for your help!
So here's what you can do:
gather all icecream/cupcakes count data into a dictionary
icecream_dict = {obj['date']: obj['count'] for obj in ice_creams}
cupcakes_dict = {obj['date']: obj['count'] for obj in cupcakes}
create a sorted list with all the dates
all_dates = sorted(set(list(icecream_dict.keys()) + list(cupcakes_dict.keys())))
create a list with items for each date and their count
result = []
for each_date in all_dates:
total_ice_creams = icecream_dict.get(each_date, 0)
total_cupcakes = cupcakes_dict.get(each_date, 0)
res = {
'date': each_date,
'total_ice_creams': total_ice_creams,
'total_cupcakes': total_cupcakes,
'total_dessert': total_ice_creams + total_cupcakes
}
result.append(res)
# check the result
print(result)
Hint: If you plan to add more desert-like models, consider have a base model Desert that you could query directly instead of querying each desert type model.

Get Hourly based sum in django

I have a model which contains two fields DateTimeField and an IntegerField.
I want to sum the total integers on the basis of hour.
class ModelA(models.Model):
date_time = models.DateTimeField()
relative_change = models.IntegerField()
Now i want to query the modelA so that it will return the total sum of relative_change for each hour,What's the good way to do it?
I checked this stackoverflow question but i am not clear what is 'hour' there.
The Output should look like
[
{
"time":"9-10",
"relative_change":"20"
},
{
"time":"10-11",
"relative_change":"40"
},
{
"time":"11-12",
"relative_change":12
}
]
This should do it:
from django.db.models import Sum
queryset = (
ModelA
.objects
.values('date_time__hour')
.annotate(relative_change_sum=Sum('relative_change')
)
You should expect the following result:
<QuerySet [{
'date_time__hour': 9,
'relative_change_sum': 20,
}, {
'date_time__hour': 10,
'relative_change_sum': 40,
}]
Here's more details about the 'hour' lookup:
https://docs.djangoproject.com/en/2.2/ref/models/querysets/#hour

Power BI - DAX measure to reference a list of values. Calculate net turnover per broker - more elegant solution?

Below is a simplified version of transaction data for stocks.
StockData =
DATATABLE (
"STOCK", STRING,
"Date", DATETIME,
"Buyer", STRING,
"Seller", STRING,
"Turnover", INTEGER,
{
{ "AAPL", "2019/04/07", "GSI", "BRC", 100 },
{ "AAPL", "2019/04/07", "CITI", "JPM", 500 },
{ "AAPL", "2019/04/07", "JPM", "GSI", 700 },
{ "AAPL", "2019/04/08", "GSI", "JPM", 300 },
{ "AAPL", "2019/04/08", "GSI", "CITI", 800 },
{ "AAPL", "2019/04/08", "JPM", "BRC", 400 },
{ "MSFT", "2019/04/07", "GSI", "GSI", 500 },
{ "MSFT", "2019/04/07", "JPM", "BRC", 700 },
{ "MSFT", "2019/04/07", "BRC", "GSI", 800 },
{ "MSFT", "2019/04/08", "GSI", "BRC", 500 },
{ "MSFT", "2019/04/08", "GSI", "JPM", 600 },
{ "MSFT", "2019/04/08", "CITI", "BRC", 500 }
}
)
Goal is to calculate net turnover by broker per day.
I can achieve this by following DAX measure
Test BRC Net Turnover =
VAR TotalBuy = CALCULATE(SUM(StockData[Turnover]),StockData[Buyer] = "BRC")
VAR TotalSell = CALCULATE(SUM(StockData[Turnover]),StockData[Seller] = "BRC")
Return TotalBuy - TotalSell
However, to get net turnover for all (Four) brokers in example data above I have to rewrite the measure four times with different critera, i.e., rather than using "BRC" I have to use "GSI" etc...
Real data set consists of 50 different broker codes so the solution with 50 different measures is not feasible.
How can I make this DAX function iterate over all Broker codes in my data set. Taking into consideration filters for the stock. I.e., if a typical broker code doesnt exist for MSFT but for AAPL the measure will take that into consideration.
I have tried the values function to return a list of all brokers, without any success.
Above is what I would like to achieve with one single measure.
Many thanks
Exemplary well-written question!
To do this, let's first create an independent calculated table to use for the different buyers and sellers.
Brokers = VALUES( StockData[Buyer] )
Now we can put Brokers[Buyer] in the Legend field and write a measure that reads that value.
Net Turnover =
VAR Broker = SELECTEDVALUE ( Brokers[Buyer] )
VAR TotalBuy = CALCULATE ( SUM ( StockData[Turnover] ), StockData[Buyer] = Broker )
VAR TotalSell = CALCULATE ( SUM ( StockData[Turnover] ), StockData[Seller] = Broker )
RETURN
TotalBuy - TotalSell