【问题标题】:Get the foreign key field using Peewee ORM使用 Peewee ORM 获取外键字段
【发布时间】:2015-08-06 16:31:53
【问题描述】:

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

我想通过 Act.id 选择 post_title、user_name、act_title(act 中的默认主键)。

所以我用这个

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

但我得到了这个: [{"post_title": null,"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)

【问题讨论】:

  • 为您的课程使用模拟表,看起来您的选择应该可以工作。就调试而言,您尝试过什么?您使用的是什么类型的数据库? Act中是否存在actId中的值?
  • 我正在使用 Mysql,并且在我的 json 数据中得到了这个 "post_content": "\u597d", "user": {}, "act": {}

标签: python orm peewee


【解决方案1】:

如果你想在 Post 表上同时加入 User 和 Act 表,你需要在查询中放一个 switch,这样你就有

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

虽然这可能不是您正在寻找的结果,因为您在 Act 和 Post 模型中都将 user 作为外键

【讨论】:

  • 我试过了,但我仍然没有从 user 和 act 那里得到任何东西......只是这个 "post_content": "\u597d", "user": {}, "act": {}..
【解决方案2】:

我认为您唯一缺少的就是不查找连接实例上的值:

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())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-01
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 2020-11-26
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多