João Elvas
João Elvas

Reputation: 113

Peewee inserting without foreign keys

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?

Upvotes: 1

Views: 709

Answers (2)

coleifer
coleifer

Reputation: 26235

I agree with looking into the db. If you're using SQLite, make sure PRAGMA foreign_keys=ON to get them enforced.

Upvotes: 1

gms
gms

Reputation: 335

The foreign key is the right way to do it (like you did) but the tables must be InnoDB. If the tables are MyISAM than there isn't any foreign key restrain because MyISAM don't use foreign keys. So, are your tables InnoDB?

(I wanted to comment and not to post an answer but my reputation is too low to do it ...)

Upvotes: 0

Related Questions