r/FastAPI • • Mar 29 '21

Question How to handle many-to-many relationships?

Hello peps,

I'm building a simple service with fastapi. I'll try to present my problem in the easiest way I can :)

Let's say I have two entities: Person and Animal. The relationship is like "likes", so my dude Mark is a cat person but also loves horses, while Katia is a huge dog fan.

I'm talking about the generic animal, not a particular one, so the "Animals" are reusable... and thank god, since each of them also has a huge photo that weights several megabytes, to show the fluff

I would have something like this

association_table = Table(
'association', Base.metadata,
Column('person_id', String, ForeignKey('people.id')),
Column('animal_id', String, ForeignKey('animals.id'))
)

class Person(Base):
id = Column(String, primary_key = True)
name = Column(String)
animals = relationship("Animal", secondary=association_table, backref="people")

class Animal(Base):
id = Column(String, primary_key = True)
photo = Column(String) # base 64

Don't consider the names or the fact that the primary key is a string, in the real app it all makes sense.

Now, I want an endpoint to GET and POST/PUT a Person. Problem is, how do I handle the relationship?

I would like to allow a List of primary keys (strings in this case) as the input (and then the post function will take care of linking that to the actual animal), and also to get a list of primary keys instead of the whole animal entity, so that I can get something like

{

"id": "...",

"name": "Mark",

"animals": ["cat", "horse"]

}

This way, on my frontend I would download all the animals (or keep a cache, whatever), and then link them to each person as need be, instead of downloading the same cat 100 times because everybody loves cats

I tried something like this

def get(self, db: Session, id: str):
person = db.query(Person).filter(Person.id == id).first()
person.animals = [animal.id for animal in person.animals]

return person

But that fails because of

AttributeError: 'str' object has no attribute '_sa_instance_state'

Because I guess it's doing a type-checking against the sqlalchemy model (not the pydantic one)

def get(self, db: Session, id: str):
person = db.query(Person).filter(Person.id == id).first()
person.likedAnimals = [animal.id for animal in person.animals]

return person

This one "works" in the sense that it actually adds the field, and with pydantic models I can "hide" the original animals... but my understanding is that it's still being downloaded in full, it's just not showing it.

This seems like and extremely basic thing to do and clearly I'm missing something, because I find it hard to implement. Any suggestion will be very welcome!

2 Upvotes

2 comments sorted by

2

u/PhilosophicalSanders Mar 30 '21

I apologize — on mobile so I’ll link instead; I’ll try and update with some working examples a bit later:

However, where you see Relationship(“Table-as-String”, ...), instead, do import Package.Module.TableName as Table, and assign the association Relationship(Table, ...) (it’s a nice little trick that they don’t necessarily mention in the documentation).

On the pydantic side, just type alias the reference schema, or use the foreign key type and ensure use_orm = True.

Again I’ll update later with more defined examples.

1

u/Expensive-Letterhead Mar 31 '21

Thank you for your reply! I asked on gitter too and someone was kind enough to point me in the right direction!

I needed to do queries like this

db.query(Person).options(selectinload(Person.animals).load_only(Animal.id))

It returns animals like

[

{ "id": "cat"},

{"id": "dog"}

]

Not exactly as nice as I would've liked it to be (["cat", "dog"]), but good enough :D