如何使用带有现有数据的peewee插入sqlite数据库

时间:2019-02-19 04:51:31

标签: python sql sqlite peewee

因此,我正在考虑使用peewee创建一个sqlite体育数据库,并且试图弄清楚如何将数据插入到已经为某些表插入的数据库中。

例如,我有这段代码在循环的第一次运行中运行良好,但是由于已经定义了竞技场“ mackey”,因此在第二个循环上引发了IntegrityError。

如何编写它,以便它第二次运行通过循环,它识别出“印第安纳州西拉斐特”的“ Mackey Arena”已经创建,并使用该场所ID,而不是创建第二个场所行?

from peewee import *

db = SqliteDatabase('pndb.db')

class Venue(Model):
    Name = CharField(unique = True)
    City = CharField()
    State = CharField()

    class Meta:
        database = db


class Team(Model):
    Name = CharField(unique = True)

    class Meta:
        database = db

class Game(Model):

    DateTime = DateTimeField()
    NeutralSite = BooleanField()
    ConferenceMatchup = BooleanField()
    venue = ForeignKeyField(Venue)
    Attendance = IntegerField()
    Status = CharField()

    class Meta:
        database = db

class TeamGame(Model):

    game = ForeignKeyField(Game)
    team = ForeignKeyField(Team)
    HomeAway = CharField()

    class Meta:
        database = db 





db.connect()
db.create_tables([Game,Venue,TeamGame,Team])

from datetime import date

for i in range(1,5):

    mackey = Venue.create(Name = 'Mackey Arena',City = 'West Lafayette',State = 'Indiana')

    purdue = Team.create(Name = 'Purdue')

    pGame = Game.create(DateTime = date(2019,i,2),NeutralSite = False, ConferenceMatchup = True, venue = mackey,Attendance = 3000,Status = 'completed')

    tG = TeamGame.create(game = pGame,team = purdue, HomeAway = 'Home')

    tG.save()

1 个答案:

答案 0 :(得分:0)

有很多方法,这取决于您如何导入数据。您可以使用dictset或其他方法来跟踪插入到内存中的对象,如果您一次加载所有内容并且可能有重复项,则可以使用此功能。

或者,您可以捕获违反数据库约束时引发的peewee.IntegrityError错误。例如:

try:
    # Create new user. Assume a UNIQUE constraint on username.
    user = User.create(username=username)
except IntegrityError:
    # Already exists, grab from db.
    user = User.get(User.username == username)

但是,这可能会效率低下,因为如果您预计会重复很多,则可能要执行两个查询。要解决此问题,您可以尝试结合我描述的两种方法。