Skip to content

How to cascade insertions into association table for many-to-many relationships #134

Answered by shrir
shrir asked this question in Q&A
Discussion options

You must be logged in to vote

Thanks @Alc-Alc, I figured it out!

Here's what's different:

  1. My code is running as a domain service in Litestar.
  2. I am converting a dict to a Book model using to_model() before create().

Here's the code snippet:

service = BookService(session=db_session)
author = Author("AB") # Author already exists in db
book_dict = {"title": "My Book", "authors": [author]}
book = service.to_model(book_dict, "create")
service.create(book)

book.authors is an empty list in the Book object returned by to_model().
When I handle this explicitly(book.authors = book_dict["authors"]), everything works!

Learning: Relationships need to be handled manually when using to_model() 🤔

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by shrir
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants