piccolo icon indicating copy to clipboard operation
piccolo copied to clipboard

One-to-many relations

Open McSlow opened this issue 5 years ago • 6 comments

Hi, i'm currently having some beginner issues with one-to-many relations. Given the following scheme:

class Manager(Table):
    id = PrimaryKey()
    name = Varchar()

class Band(Table):
    id = PrimaryKey()
    name = Varchar()
    manager = ForeignKey(references=Manager)
    popularity = Integer()

How can I access all Bands a Manager manages? So something like bandsAManagerManages = Manager.bands Is there some automatic support for such things or do I need to write a function with a subquery in the Manager table (... .where(manager=self.id)?

McSlow avatar Sep 06 '21 20:09 McSlow

Hi @McSlow

If you just just want to find the bands for a single manager, you can do something like:

manager = Manager.objects().get(Manager.name == 'Guido').run_sync()

>>> Band.objects().where(Band.manager == manager).run_sync()
[<Band: 1>]

There isn't an API yet to bulk retrieve all of the bands for all of the managers (i.e. reverse foreign key lookups), but it's something we're working on.

If that's your use case, you might find this discussion useful: https://github.com/piccolo-orm/piccolo/discussions/208

dantownsend avatar Sep 06 '21 21:09 dantownsend

Thanks- that was fast :) Reverse foreign key lookups would be cool, but the provided example already does exactly what I want :) Just need to find out how to add this as an rest endpoint to fastAPi ( /manager/1/bands) but I guess I'll find out...

McSlow avatar Sep 06 '21 21:09 McSlow

The best way to see how it all hangs together with FastAPI, is use piccolo asgi new (assuming it's a new project). That includes some example endpoints.

dantownsend avatar Sep 06 '21 21:09 dantownsend

Ah ok- that was really easy, got it. Thanks again :)

McSlow avatar Sep 06 '21 21:09 McSlow

Any news on this? There is already working m2m functionality for selecting related tables await Band.select(Band.name, Band.genres(Genre.id, Genre.name)), so it can be applied for reverse one-to-many lookups.

metakot avatar Oct 17 '22 11:10 metakot

@metakot We have a prototype for this in a PR - https://github.com/piccolo-orm/piccolo/pull/599. Hopefully will get it merged soon.

dantownsend avatar Oct 17 '22 20:10 dantownsend