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

Python peewee foreign keys

Hello guys,

So I asked this on stackoverflow yesterday but I still did not get any answer.

So iam using peewee to create databases in python.

class BaseModel(Model):
    class Meta:
        database = db

class Phone(BaseModel):
    '''Phone database model.'''
     model = CharField(max_length=15, unique=True, primary_key=True)

class Imei(BaseModel):
    '''Imei database model.'''
    imei = CharField(max_length=15, unique=True, primary_key=True)
    model = ForeignKeyField(Phone, to_field="model", related_name="imei's from model")
    registered = BooleanField(default=False)
    timestamp = DateTimeField(default=datetime.datetime(2014, 1, 1, 0, 0))
    email = CharField(max_length=50, null=True)

What I want to achieve here is that whenever I insert on "Imei" table, it does not insert if the model is not listed on the "Phone" table.

I did that using foreign key, but the problem is that when I insert on imei table, with the phone table empty, it inserts with no problem.

How can I solve this?

Kenneth Love can you give a look please?