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(*))
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 have a tuple list which looks like this:
val days= List(("Sunday", 1), ("Monday", 2), ("Tuesday", 1),
("Wednesday", 2), ("Thursday", 3), ("Friday", 2),
("Saturday", 3))
I want the final result to look like this:
"data": [
[
"Sunday, 1",
"Tuesday, 1"
],
[
"Monday, 2",
"Friday, 2"
"Wednesday,2"
],
[
"Thursday, 3",
"Saturday,3"
]
]
You can group and then map values:
days.groupBy(_._2)
.mapValues(_.map { case (name, nr) => s"$name, $nr" } )
.valuesIterator.toList
The result is:
List(List(Monday, 2, Wednesday, 2, Friday, 2), List(Sunday, 1, Tuesday, 1), List(Thursday, 3, Saturday, 3))
P.S.: As Luis Miguel Mejía Suárez suggests, using groupMap (from scala 2.13) can make this a bit more concise and readable:
days.groupMap(_._2) { case (name, nr) => s"$name, $nr" }
.valuesIterator.toList
I have a following nested dictionary which is not a list of lists, but dictionary within dictionary.
MYDICT = {
"groupA": {
"teamA": {
"won": 0,
"lost": 1,
},
"teamB": {
"won": 1,
"lost": 2,
}
},
"groupB": {
"teamC": {
"won": 1,
"lost": 2,
},
"teamD": {
"won": 7,
"lost": 3,
}
}
}
I'd like to sort it within each group by "won" field. The result should look like:
{
"groupA": {
"teamB": {
"won": 1,
"lost": 2,
},
"teamA": {
"won": 0,
"lost": 1,
}
},
"groupB": {
"teamD": {
"won": 7,
"lost": 3,
},
"teamC": {
"won": 1,
"lost": 2,
}
}
}
The code I tried so far was
newd = {k: dict(sorted(v.items(), key=lambda x: x[2], reverse=True)) for k, v in MYDICT.items()}
but it is returning following error
IndexError: tuple index out of range
so clearly I am probably not reaching proper level to sort.
EDIT 1: I don't think this is possible with only one lambda. I changed my strategy and started iterating over given levels
new_sorted=OrderedDict()
print('MYDICT: {}'.format(jd(MYDICT)))
for item in MYDICT:
sorted_elements = sorted(MYDICT[item], key=lambda x: (MYDICT[item][x]['won']), reverse=True)
for se in sorted_elements:
print('se: {}'.format(se))
new_sorted[item] = se
print('MYDICT[item][se]: {}'.format(MYDICT[item][se]))
new_sorted[item][se] = MYDICT[item][se]
print('item: {}, sorted: {}'.format(item, sorted_elements))
Now when I try to assign back these values (so actually I'm creating new ordered dictionary with sorted items) I have this error:
MYDICT: {
"groupA": {
"teamA": {
"won": 0,
"lost": 1
},
"teamB": {
"won": 1,
"lost": 2
}
},
"groupB": {
"teamD": {
"won": 7,
"lost": 3
},
"teamC": {
"won": 1,
"lost": 2
}
}
}
se: teamB
MYDICT[item][se]: {'won': 1, 'lost': 2}
Traceback (most recent call last):
File "ordered_dict.py", line 124, in <module>
new_sorted[item][se] = MYDICT[item][se]
TypeError: 'str' object does not support item assignment
Any help would be appreciated.
Your code
newd = {k: dict(sorted(v.items(), key=lambda x: x[2], reverse=True))
for k, v in MYDICT.items()}
is getting there.
The second element (value) is just x[1], not x[2], since tuple indexes start at 0 in Python.
You want to sort not on the value directly, but the value’s "won". That’s x[1]["won"].
You need OrderedDict, like your other snippet, since plain Python 2.7 dicts aren’t ordered.
So:
newd = {k: OrderedDict(sorted(v.items(), key=lambda x: x[1]["won"], reverse=True))
for k, v in MYDICT.items()}
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.
I know this is probably a very simple List operation in Scala, but I'm a newbie and can't figure it out. I have a query that returns a result set with a series of values, grouped by a common id. For example:
Result Set:
[{ 1, "a", 30 },
{ 1, "b", 20 },
{ 1, "c", 22 },
{ 2, "a", 32 },
{ 2, "c", 10 }]
and what I'd like to do is put this into a map as such:
1 -> [{"a", 30}, {"b", 20}, {"c", 22}]
2 -> [{"a", 32}, {"c", 10}]
I think the collect method can be used for this but can't figure it out.
I'm not sure what the types in your data structure are, but maybe you can adapt this. This assumes you have a collection of tuples:
val items =
List((1, "a", 30),
(1, "b", 20),
(1, "c", 22),
(2, "a", 32),
(2, "c", 10))
items
.groupBy{ case (a,b,c) => a }
.mapValues(_.map{ case (a,b,c) => (b,c) })
// Map(1 -> List((a,30), (b,20), (c,22)), 2 -> List((a,32), (c,10)))
Or, more succinctly:
items.groupBy(_._1).mapValues(_.map(t => (t._2, t._3)))
The collect method is something else entirely (basically, it's map that drops non-matching values). The groupBy method is what you were really looking for.