igorbenav / fastcrud

FastCRUD is a Python package for FastAPI, offering robust async CRUD operations and flexible endpoint creation utilities.
MIT License
530 stars 32 forks source link

Add support for update relationships #100

Open PaleNeutron opened 3 weeks ago

PaleNeutron commented 3 weeks ago

Is your feature request related to a problem? Please describe.

A very common usecase is that we want to update both a model and it's relationships (change both user name and tags in one form) in one request especially m2m relationship. Consider models below:

from sqlalchemy import create_engine, Column, Integer, String, Table, ForeignKey
from sqlalchemy.orm import relationship, declarative_base, sessionmaker

Base = declarative_base()

user_tag_association = Table('user_tag_association', Base.metadata,
    Column('user_id', Integer, ForeignKey('users.id')),
    Column('tag_id', Integer, ForeignKey('tags.id'))
)

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)

    tags = relationship('Tag', secondary=user_tag_association, back_populates='users')

class Tag(Base):
    __tablename__ = 'tags'
    id = Column(Integer, primary_key=True)
    name = Column(String)

    users = relationship('User', secondary=user_tag_association, back_populates='tags')

Describe the solution you'd like

If we can update user by passing :

{
"id": 3,
"name": "new name" 
"tags": [1,2,3]
}

That would be great

Describe alternatives you've considered

Use native sqlalchemy ORM update feature:

u = User.query.get(1)
posts_ids = [1, 2, 3]
posts = Post.query.filter(Post.id.in_(posts_ids)).all()
u.posts = posts

Additional context Add any other context or screenshots about the feature request here.