使用 Peewee ORM 获取外键字段

Get the foreign key field using Peewee ORM

我尝试使用 Peewee ORM select 一些数据,但我对如何正确使用外键感到困惑。

我想 select post_title,user_name,act_title Act.id(默认主键)。

所以我用这个

Post.select(Post.post_tile,User.user_name,Act.act_title).join(Act).join(User).where(Act.id==actId)

但我得到了这个: [{"post_title": 空,"user": {}, "act": {}}]

这是我的模型:

class User(BaseModel):
    user_name = CharField(max_length=30,unique=True) 
    user_email = CharField(max_length=60,unique=True) 

class Act(BaseModel):
    user = ForeignKeyField(User, related_name='users_act_id') #foreignkey
    act_title = CharField(max_length=30)

class Post(BaseModel):
    act = ForeignKeyField(Act,related_name='acts_id') #foreignkey
    user = ForeignKeyField(User,related_name='users_post_id') #foreignkey 
    post_title = CharField(max_length=30)

如果您想在 Post table 上同时加入用户和行为 table,您需要在查询中添加一个 switch,这样您会有

Post.select(Post.post_tile,User.user_name,Act.act_title).join(Act).switch(Post).join(User).where(Act.id==actId)

尽管这可能不是您要查找的结果,因为您在 Act 和 Post 模型中都将用户作为外键

我认为您唯一缺少的是没有查找已连接实例的值:

posts = (Post
         .select(Post.post_tile,User.user_name,Act.act_title)
         .join(Act)
         .switch(Post)
         .join(User)
         .where(Act.id==actId))
for post in posts:
    print post.post_title, post.user.user_name, post.act.act_title

如果您想要将属性全部分配给 post 对象,只需添加对 .naive() 的调用,例如:

posts = (Post.select()...where(Act.id==actId).naive())