'How to update one to many relationship sqlalchemy and FastAPI?

I have the following one-to-many relationship in SQLAlchemy.

models/user.py

class User(Base):
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    created_date = Column(DateTime, default=datetime.datetime.utcnow, index=True)
    name = Column(String)
    phone = Column(String, index=True)
    email = Column(String, index=True)
    status = Column("status", Enum(Status))
    orders: List[Order] = relationship("Order", back_populates="users")

models/order.py

class Order(Base):
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    created_date = Column(DateTime, default=datetime.datetime.utcnow, index=True)
    fullfiled_date = Column(DateTime, index=True)
    size = Column(String)
    flavour = Column(String)
    topping = Column(String)
    frosting = Column(String)
    price = Column(Float, index=True)
    user_id = Column(UUID(as_uuid=True), ForeignKey("user.id"), default=uuid.uuid4)
    users = relationship("User", back_populates="orders")

data_access_layer

class UserDAL:
    def __init__(self, db_session: Session):
        self.db_session = db_session

    async def fetch_user_by_email(self, email: str):
        user = await self.db_session.execute(select(User).filter(User.email == email))
        return user.scalar_one_or_none()

    async def record_order(self, u: Customer, c: Cake, price: float):
        user = await self.fetch_user_by_email(u.email)

        if not user:
            user = User(name=u.name, email=u.email)
            self.db_session.add(user)
            await self.db_session.flush()

        order = Order(
            size=c.size,
            flavour=c.flavour,
            frosting=c.frosting,
            topping=c.topping,
            price=price,
        )

        orders = await self.db_session.execute(
            select(Order).where(Order.user_id.in_(user.orders))
        )

        for o in orders.scalars.all():
            user.orders.append(o)

        await self.db_session.commit()

        return order

To put the relationship in words, "one user can have multiple orders and orders can be associated to one single user".

I am trying to associate the user order in orders field which is a relationship with Order model as define above. Right now I am getting this error:

sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_() here. Was IO attempted in an unexpected place?

How can I associate user with orders properly in async way?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source