one в User и в него надо добавить Exchange запись.
Не могу разобраться
class User(BaseModel):
__tablename__ = "users"
user_id = Column(BigInteger, primary_key=True, nullable=False)
username = Column(VARCHAR(32), unique=False, nullable=True)
ip = Column(VARCHAR(32), unique=True, nullable=True)
deviceId = Column(VARCHAR(10), unique=True, nullable=False)
exchanges: Mapped[List['Exchange']] = relationship(back_populates='user', uselist=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
def __str__(self):
return self.username
class Exchange(BaseModel):
class ExchangeStatus(Enum):
pending = 'pending'
waiting_payment = 'waiting_payment'
exchanging = 'exchanging'
finished = 'finished'
__tablename__ = "exchanges"
id = Column(Integer, unique=True, nullable=False, primary_key=True, autoincrement=True)
hash = Column(VARCHAR(10), nullable=False, unique=True)
# Exchange details
status = Column(Choice(ExchangeStatus), default='pending')
user: Mapped['User'] = relationship(back_populates="exchanges", uselist=False)
user_fk: Mapped[int] = mapped_column(ForeignKey('users.user_id'))
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
def __str__(self):
return self.username
user = User(…) exchange = Exchange(…) user.exchanges.append(exchange)
Сделал по своему, вроде отрабатывает. Но есть сомнения что не практично, что вы думаете на этот счёт? user_result = await session.execute( select(User).where(User.user_id == user_id) ) user: User = user_result.scalar() exchange = Exchange( hash=exchange_hash, user=user ) session.add(exchange) await session.merge(exchange) await session.commit()
```python print('Hello World') ``` print('Hello World')
Обсуждают сегодня