简体   繁体   中英

How to insert into sqlite database with peewee with existing data

So I'm looking into creating a sqlite sports database with peewee, and I'm trying to figure out how to insert data into the database that has already been inserted for certain tables.

For example, I have this code that runs fine on the first run through the loop, but throws an IntegrityError on the second loop since the arena "mackey" has already been defined.

How do I write it so that the second time it runs through the loop it recognizes that "Mackey Arena" in "West Lafayette, Indiana" has already been created, and uses that venue_id, instead of creating a second venue row?

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()

There are many ways, and it depends on how you're importing your data. You can keep track of the objects you've inserted in-memory using a dict or set or whatever, which works if you're loading stuff up all at once and there may be duplicates.

Alternatively, you can catch the peewee.IntegrityError error that is raised when a db constraint is violated. For example:

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)

This can be inefficient, however, as you are potentially doing two queries if you anticipate a lot of duplicates. To work around that, you can try to combine the two approaches I described.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM