Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Peewee Models ForeignKeyField class: NameError: name 'Bar' is not defined

Flask throws me this error: NameError: name 'Source' is not defined

It seems to occur when I call a Model class that is defined later in the models.py file. If I define the model before it gets called, there is no error. I could just switch the models around, but then I get into other problems, so what I really want is to do it in this order. Is there a way to do this? Thanks!

class Bar(Model):
    description = CharField(unique=True)

    class Meta:
        database = DATABASE

class Foo(Model):
    bar = ForeignKeyField(rel_model=Bar, related_name='foos')

    class Meta:
        database = DATABASE

1 Answer

Hi Bk

This is what i did and did not get any errors.

from peewee import *

DATABASE = SqliteDatabase('my_app.db')

class Bar(Model):
    description = CharField(unique=True)

    class Meta:
        database = DATABASE

class Foo(Model):
    bar = ForeignKeyField(rel_model=Bar, related_name='foos')

    class Meta:
        database = DATABASE


if __name__=='__main__':
    DATABASE.connect()
    DATABASE.create_tables([Bar, Foo],safe=True)