Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

List aggregate #766

Open
powellnorma opened this issue Feb 21, 2023 · 2 comments
Open

List aggregate #766

powellnorma opened this issue Feb 21, 2023 · 2 comments

Comments

@powellnorma
Copy link

powellnorma commented Feb 21, 2023

Let's say I have

class Subject(Table):
    name = Varchar()

class Event(Table):
    subject = ForeignKey(Subject)
    timestamp = Timestamptz()
    data = JSONB()

How can I fetch all Subject with corresponding Events given a particular timerange?
It should be possible with a 'ReverseLookup' (#599), when we use a 'RIGHT JOIN' to the subquery, I think?

Alternatively an list aggregate Function could be helpful:

  1. Events.select and group_by subject + list aggregate the rest (e.g. with json_agg in postgres)
  2. Join Subject data inside that Events.select query

Is there currently a way to do this? Thank you!

@powellnorma
Copy link
Author

It should be possible with a 'ReverseLookup' (#599), when we use a 'RIGHT JOIN' to the subquery, I think?

Alternatively, would it be possible to use the ReverseLookup in the where clause? So that where and select can use two different Subqueries (ReverseLookups)

@dantownsend
Copy link
Member

dantownsend commented Feb 22, 2023

Yeah, it's not possible with a single query currently.

Something like this should work:

events = await Event.select(
    Event.subject.name.as_alias('event_name'),
    Event.data
).where(Event.timestamp > some_timestamp).order_by(Event.subject)

grouped = {
    key: list(group) for key, group in itertools.groupby(
        events,
        lambda event: event['event_name']
    )
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants