[英]Get the foreign key field using Peewee ORM
I trying to select some data using Peewee ORM,but I'm confused how to use foreign key correctly. 我试图使用Peewee ORM选择一些数据,但是我对如何正确使用外键感到困惑。
I wanna select post_title,user_name,act_title by Act.id(default primary key in act). 我想通过Act.id(行为中的默认主键)选择post_title,user_name,act_title。
So I use this 所以我用这个
Post.select(Post.post_tile,User.user_name,Act.act_title).join(Act).join(User).where(Act.id==actId)
But I got this: [{"post_title": null,"user": {}, "act": {}}] 但是我得到了这个:[{“ post_title”:null,“ user”:{},“ act”:{}}]
Here is my model: 这是我的模型:
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)
If you want to join both the User and the Act table on the Post table, you need to put a switch in the query, so you would have 如果要同时将“用户”表和“行为”表连接到“发布”表上,则需要在查询中放置一个开关 ,这样就可以
Post.select(Post.post_tile,User.user_name,Act.act_title).join(Act).switch(Post).join(User).where(Act.id==actId)
Although it's possible that's not the result you're looking for because you have user as a foreign key in both the Act and Post models 尽管可能不是您想要的结果,因为在Act和Post模型中都将用户作为外键
I think the only thing you're missing is not looking up the values on the joined instances: 我认为您唯一缺少的是不查找联接实例上的值:
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
If you want the attributes all assigned to the post
object, just tack on a call to .naive()
, eg: 如果希望将所有属性全部分配给post
对象,则只需添加对.naive()
的调用即可,例如:
posts = (Post.select()...where(Act.id==actId).naive())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.