简体   繁体   中英

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.

I wanna select post_title,user_name,act_title by Act.id(default primary key in act).

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": {}}]

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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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