I have two tables:
Ticket Table
id paid_with_tax
1 5
2 6
3 7
TicketAdjustment Table
id ticket_id value_with_tax
1 1 2
2 1 1
3 1 2
4 1 3
5 2 5
The query I use:
use = 0
Ticket.objects.all().annotate(
paid_amount=Sum(
F('paid_with_tax') +
Coalesce(F('ticketadjustment__value_with_tax'), 0) * use
)
)
the query would return the following:
[
{id: 1, paid_amount: 7},
{id: 1, paid_amount: 6},
{id: 1, paid_amount: 7},
{id: 1, paid_amount: 8},
{id: 2, paid_amount: 11},
{id: 3, paid_amount: 7},
]
but the above is incorrect since the Ticket Table id=1 values are duplicated by the TicketAdjustment Table values.
how can i get the query to sum the TicketAdjustment Table values and return the following:
[
{id: 1, paid_amount: 13},
{id: 2, paid_amount: 11},
{id: 3, paid_amount: 7},
]
Here the solution for your problem :
Ticket.objects.all().annotate(
paid_amount=(F('paid_with_tax') +
Sum(Coalesce(F('ticketadjustment__value_with_tax'), 0))
)
).values_list('id', 'paid_amount')
values_list select the field you want in your result.
In your primary request there is a big problem.
Sum(F('paid_with_tax') + Coalesce(F('ticketadjustment__value_with_tax'), 0) * use)
This ligne miltiply value_with_tax with zero. So give you zero. It's like :
Sum(F('paid_with_tax'))
You want the sum of value_with_tax for each ticket, this is why I move Sum on it :
Sum(Coalesce(F('ticketadjustment__value_with_tax'), 0))
And after add the value of paid_with_tax
NB : I remove your variable use, because don't know is goal.
Related
I have some object references of a class like this:
Patient patientOne = Patient('Person A', 'https://images.unsplash.com/photo-1545996124-0501ebae84d0?ixid=MXwxMjA3fDB8MHxzZWFyY2h8OHx8aHVtYW58ZW58MHx8MHw%3D&ixlib=rb-1.2.1&w=1000&q=80',
8, 2, 'Pending', '10-08-2015', true);
Patient patientTwo = Patient('Person B', 'https://images.unsplash.com/photo-1544005313-94ddf0286df2?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTF8fGh1bWFufGVufDB8fDB8&ixlib=rb-1.2.1&w=1000&q=80',
8, 5, 'Cancel', '23-12-2019', false);
Patient patientThree = Patient('Person C', 'https://images.unsplash.com/photo-1554151228-14d9def656e4?ixid=MXwxMjA3fDB8MHxzZWFyY2h8NHx8aHVtYW58ZW58MHx8MHw%3D&ixlib=rb-1.2.1&w=1000&q=80',
8, 7, 'Cancel', '01-02-2019', false);
Patient patientFour = Patient('Person D', 'https://upload.wikimedia.org/wikipedia/commons/e/ec/Woman_7.jpg',
8, 4, 'Pending', '20-09-2018', true);
Patient patientFive = Patient('Person E', 'https://cdn.pixabay.com/photo/2017/08/07/14/15/portrait-2604283__340.jpg',
8, 6, 'Pending', '28-04-2017', false);
I want to store those reference variables (patientOne , patientTwo ... patientFive ) into a list.
How to do that ?
final List<Patient> patients = <Patient>[];
patients.addAll([patientOne,patientTwo,patientThree,...]);
or
final List<Patient> patients = [
Patient('Person A', 'https://images.unsplash.com/photo-1545996124-0501ebae84d0?ixid=MXwxMjA3fDB8MHxzZWFyY2h8OHx8aHVtYW58ZW58MHx8MHw%3D&ixlib=rb-1.2.1&w=1000&q=80',
8, 2, 'Pending', '10-08-2015', true),
Patient('Person A', 'https://images.unsplash.com/photo-1545996124-0501ebae84d0?ixid=MXwxMjA3fDB8MHxzZWFyY2h8OHx8aHVtYW58ZW58MHx8MHw%3D&ixlib=rb-1.2.1&w=1000&q=80',
8, 2, 'Pending', '10-08-2015', true)
,...
] ;
I'm new to postgREST. I've set it up and it's working fine with my db. I'm going through the docs and I think I could use of Resource Embedding, but I can't figure out how to make it work in a nested way.
My schema has tables similar to the following:
create table ta (
a_id integer primary key,
a_desc varchar(50)
);
create table tb (
b_id integer primary key,
a_id integer not null,
b_desc varchar(50),
constraint tb_fk1 foreign key (a_id) references ta(a_id)
);
create table tc (
c_id integer primary key,
b_id integer not null,
c_desc varchar(50),
constraint tc_fk1 foreign key (b_id) references tb(b_id)
);
insert into ta values (1, 'a1');
insert into tb values (1, 1, 'b1');
insert into tb values (2, 1, 'b2');
insert into tc values (1, 1, 'c1');
insert into tc values (2, 1, 'c2');
insert into tc values (3, 2, 'c3');
insert into tc values (4, 2, 'c4');
Resource embedding works when I select ta an tb:
localhost:3000/ta?select=*,tb(*)
[
{
"a_id": 1,
"a_desc": "a1",
"tb": [
{
"b_id": 1,
"a_id": 1,
"b_desc": "b1"
},
{
"b_id": 2,
"a_id": 1,
"b_desc": "b2"
}
]
}
]
It also works with tb and tc:
localhost:3000/tb?select=*,tc(*)
[
{
"b_id": 1,
"a_id": 1,
"b_desc": "b1",
"tc": [
{
"c_id": 1,
"b_id": 1,
"c_desc": "c1"
},
{
"c_id": 2,
"b_id": 1,
"c_desc": "c2"
}
]
},
{
"b_id": 2,
"a_id": 1,
"b_desc": "b2",
"tc": [
{
"c_id": 3,
"b_id": 2,
"c_desc": "c3"
},
{
"c_id": 4,
"b_id": 2,
"c_desc": "c4"
}
]
}
]
But I don't know how to make it work from ta through tc, kind of combining both queries.
Does anyone know how I could achieve this? Preferably using a query string, but working with views or stored procedures would be ok too.
Thanks in advance for any help on this.
PS: Using Potstgres 12 and postgREST 7
For nested resource embedding, you can do:
GET localhost:3000/ta?select=*,tb(*,tc(*))
I have created Highcharts graph by this code:
def chart_data(request):
dataset = DispatchPlan.objects.annotate(month=TruncMonth('scheduled_date')).values('month').annotate(
c=Sum('weight')).values('month', 'c')
chart = {
'chart': {'type': 'column'},
'title': {'text': 'Weight Dispatched by Months'},
'series': [{
'name': 'Months',
'data': [{'name': row['month'], 'y': row["c"]} for row in dataset]
}]
}
return JsonResponse(chart)
How can I add the X axis labels such that it shows month name instead of 0 and 1 ?
This is the one row of dataset from which the graph is plotted
{'month': datetime.datetime(2019, 6, 1, 0, 0, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>), 'c': 17600}
Try to use strftime (documentation) like that :
{'month': datetime.datetime(2019, 6, 1, 0, 0, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>).strftime("%B"), 'c': 17600}
I have the following table:
2018-01-01 ------- 10
2018-01-15 ------- 20
2018-01-31 ------- 30
2018-02-01 ------- 10
2018-03-01 ------- 10
2018-03-20 ------- 20
I need to Sum the values filtering it with
1 - sum(values) where date < the first day of the month
2 - sum(values) where date < last day of the month
Expected result(something like that):
[
{'year-month': '2018-01'}, {'sum_before_month_day_one': 0}, {'sum_before_last_month_day': 60},
{'year-month': '2018-02'}, {'sum_before_month_day_one': 60}, {'sum_before_last_month_day': 70},
{'year-month': '2018-03'}, {'sum_before_month_day_one': 70}, {'sum_before_last_month_day': 100},
]
I found this on docs: https://docs.djangoproject.com/en/2.0/topics/db/aggregation/#filtering-on-annotations
But, I don't know to provide args to Q based by own query annotation.
So far I manage to sum values and group by month:
In [12]: result = Sale.objects \
...: .annotate(date=TruncMonth('event_date')) \
...: .values('date') \
...: .annotate(quantity=Sum('quantity')) \
...: .values('date', 'quantity') \
...: .order_by('date')
In [13]: for i in result: print(i)
{'date': datetime.date(2018, 1, 1), 'quantity': 60.0}
{'date': datetime.date(2018, 2, 1), 'quantity': 10.0}
{'date': datetime.date(2018, 3, 1), 'quantity': 30.0}
I looked around and couldn't find a good answer for this, and I'm completely new to Mongo so here is the thing if someone can help.
I have a collection in mongo which holds user related data, in this manner:
{user: 4, rate: 2, location: 1}
{user: 5, rate: 4, location: 1}
{user: 6, rate: 3, location: 1}
{user: 5, rate: 2, location: 1}
{user: 4, rate: 5, location: 1}
...
{user: x, rate: y, location: z}
Now I need a query that will return me all the users on certain location (here is 1 but can be anything) together with final sum of all the rates for that user, and all that ordered by that same sum of rates (hope this makes sense). So something like this :
{4: 7, 5: 6, 6: 3} -> {user: sum(rate)} - ordered by sum(rate)
Any ideas guys?
I will be doing this in mongoengine for Django so if anyone knows how to do this there cool, but if not I'll just do a raw query so any help is good.
Thanks a bunch!
The MongoDB feature you are looking for is the Aggregation Framework.
Here is an example query in the mongo shell:
db.collection.aggregate(
// Find matching documents (can take advantage of suitable index if present)
{ $match: {
location: 1
}},
// Add up rates by user
{ $group: {
_id: "$user",
rates: { $sum: "$rate" }
}},
// Order by total rates (ascending)
{ $sort: { rates: 1 }}
)
Sample results given your data in the question:
[
{
"_id" : 6,
"rates" : 3
},
{
"_id" : 5,
"rates" : 6
},
{
"_id" : 4,
"rates" : 7
}
]
As an optional step in the aggregation, you might want to use $project to rename the grouped _id field to user.