[英]Get the foreign key field using Peewee ORM
我试图使用Peewee ORM选择一些数据,但是我对如何正确使用外键感到困惑。
我想通过Act.id(行为中的默认主键)选择post_title,user_name,act_title。
所以我用这个
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)
如果要同时将“用户”表和“行为”表连接到“发布”表上,则需要在查询中放置一个开关 ,这样就可以
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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.