Search code examples
pythonsqlclassforeign-keyspeewee

Peewee, Python, get data in column foreign key


Hi I have a database and 2 tables,

color: color_id | color_name | color_type
fruit: fruit_id | color | fruit_name

My 'color' in fruit's table is a foreignkey draging to 'color_id' in color's table.

So, with Peewee & Python I want to get 'color' in fruit's table, but I alsways receive a 'None'.

fruits= Fruit.select() 
for fruit in fruits:    
     c = fruit.color   
     print(c)

I tried with

fruits = Fruit.get()

But here I can't iterate with it. I show you my model:

class Fruit(BaseModel):
    fruit_id= CharField()
    name = Charfield()
    color= ForeignKeyField(column_name='color', field='color', model=Color, null=True)

    class Meta:
        table_name = 'fruit'

Do you have any idea how I can get the value inside my column 'color' in my table 'fruit' ? Thanx


Solution

  • Remove the "field=" parameter, as that is not necessary and should only be specified if you need to reference a specific (non-primary-key) field on the related model:

    class Fruit(BaseModel):
        fruit_id = CharField()
        name = Charfield()
        color = ForeignKeyField(Color, column_name='color', null=True)
    
        class Meta:
            table_name = 'fruit
    

    Just for reference, iterating over fruits and accessing the color is an example of O(n) queries. You're better off doing this, which joins on the color table and selects the color columns in addition to the fruit columns:

    query = Fruit.select(Fruit, Color).join(Color)
    for fruit in query:
        print(fruit.name, fruit.color.color_name)