I'm trying to create a tables in Flask app.
For creating DB I use peewee library.
When run func, I receive an error: NOT NULL constraint failed: Time.start
Can some one explain how to insert data in to database correctly
models.py
from peewee import *
db = SqliteDatabase('report.db')
class MainModel(Model):
id = PrimaryKeyField(null=False)
class Meta:
order_by = 'id'
database = db
class Drivers(MainModel):
code = CharField()
name = CharField()
class Meta:
db_table = 'Drivers'
class Time(MainModel):
name = ForeignKeyField(Drivers)
start = IntegerField()
class Meta:
db_table = 'Time'
My script for insert data to database:
from reports.report import parse_racer_team, build_report, read_file, parse_time_lap
from models import Drivers, Time , db
DATA = 'data/'
def incert_drivers_data(path):
drivers = parse_racer_team(path)
start = read_file(path + 'start.log')
end = read_file(path + 'end.log')
for item in drivers.items():
Drivers(
code=item[0],
name=item[1]
).save()
for name in Drivers.select():
Time(
name=name.name
).save()
for time in start:
Time(
start=time
).save()
Drivers.create_table()
Time.create_table()
incert_drivers_data(DATA)
content of start.log is : [('SVF', '2018-05-24 12:02:58.917'), ('NHR', '2018-05-24 12:02:49.914'), ('FAM', '2018-05-24 12:13:04.512'), ('KRF', '2018-05-24 12:03:01.250')]
Please help me understand my mistakes.
The solution turned out to be to combine all the data that is needed into one dictionary with one key and value in the form of a list As a result, through the loop it turned out to push the data into the desired columns the first time. peewee, apparently, is picky about models, since you need to enter all the fields into the model at once. If you do it separately, then the data will not be entered (There will be an error
peewee.IntegrityError: NOT NULL constraint failed) As the problem was solved, it turned out that data is not created throughsave()(as it was written in the documentation). All work with the creation of new objects goes throughcreate(). Then there was a debriefing with a connected field ForeignKeyField, for a long time I could not figure out how to put the already received id into a connected field of another model. As a result, the code from the same documentation helpedmodels.py
utils.py