Search code examples
pythonormpeewee

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)

Solution

  • 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(), e.g.:

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