Search code examples
pythonpeewee

Join 3 table in peewee


I want to be able to join multiple tables in peewee. the scenario is a little difficult for me to figure out how to get it to work with peewee. I have the following tables: user,product,images

this is my models:

class user(BaseModel):
    id = AutoField(primary_key=True)
    username = CharField()
    password = CharField()

class product(BaseModel):
    id = AutoField(primary_key=True)
    id_user = ForeignKeyField(user)
    product_name = CharField()
    product_price = IntegerField()
    product_description = TextField()

class images(BaseModel):
    id = AutoField(primary_key=True)
    id_product = ForeignKeyField(barang)
    image_name = TextField()

i want the output like this product.id,user.username,product.product_name,product.price,product.product_description,images.image_name


Solution

  • query = (Product
             .select(Product, User, Image)
             .join_from(Product, User)
             .join_from(Product, Image))
    for product in query:
        print(product.product_name)
        print(product.id_user.username)
        print(product.images.image_name)
    

    This is all documented very thoroughly here: http://docs.peewee-orm.com/en/latest/peewee/relationships.html

    Please read the docs.