简体   繁体   English

如何使用fastapi和SQLAlchemy更新信息

[英]How to update the information using fastapi and SQLAlchemy

I am using FastAPI and SQLAlchemy. I have two ORM models users and user_profiles with foreign key relation.我正在使用 FastAPI 和 SQLAlchemy。我有两个 ORM 模型用户和具有外键关系的 user_profiles。 I am inserting data to user and user_profiles using one model我正在使用一个 model 向用户和 user_profiles 插入数据

   #1st model.
  class User():
      __tablename__: str = "user"
   #2 Model
   class UserProfile:
      __tablename__: str = "user_profiles"
     

my user request model to update the data:我的用户请求 model 更新数据:

class UserRequest():
    user_id:str=someval()

My question is how I can include user_profiles model in UserRequest and update the values.我的问题是如何在 UserRequest 中包含 user_profiles model 并更新值。

If by UserRequest you mean pydantic model, then it can be done something like this如果通过UserRequest你的意思是 pydantic model,那么它可以像这样完成

DB Models数据库模型

class User(sql.Model):
   a: str = Field()
   b: str = Field()
   properties: UserProperties = ForeignKey()

class UserProperties(sql.Model):
   c: str = Field()
   d: str = Field()

Pydantic models学究模型

class UserDTO(pydantic.BaseModel)
   a: str
   b: str

class UserPropertiesDTO(pydantic.BaseModel)
   c: str
   d: str

Then然后

def request(
   a: str,
   b: str,
   c: str,
   d: str,
) -> Response:
   User.objects.create(
      **UserDTO(a, b).dict(),
      properties=UserPropertiesDTO(c, d),
   )
   return SuccessfulResponse

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM