Python Peewee、MySQL和INSERT忽略
我在一个带有MySQL数据库的小Python脚本中使用Peewee作为ORMPython Peewee、MySQL和INSERT忽略,python,mysql,python-3.x,orm,peewee,Python,Mysql,Python 3.x,Orm,Peewee,我在一个带有MySQL数据库的小Python脚本中使用Peewee作为ORM #!/usr/bin/python3 #coding: utf-8 import peewee from peewee import * db = MySQLDatabase(**config) class Foo(peewee.Model): bar = peewee.CharField(unique=True, null=False) class Meta: database =
#!/usr/bin/python3
#coding: utf-8
import peewee
from peewee import *
db = MySQLDatabase(**config)
class Foo(peewee.Model):
bar = peewee.CharField(unique=True, null=False)
class Meta:
database = db
try:
Foo.create_table()
except:
pass
foo_data = [{'bar':'xyz'},{'bar':'xyz'}]
Foo.insert_many(foo_data).on_conflict(action='IGNORE').execute()
如你所见,我有同样的钥匙。我想第二次使用on_conflict
方法(,但仅适用于SQLite3)忽略它,但在运行脚本时出现了此错误(正常,因为未针对MySQL实现):
如果我删除.on_冲突(action='IGNORE')
,MySQL也不喜欢它(重复键)。如何让peewee插入一个新密钥,或者如果它是一个重复的密钥,则忽略它?使用db.\uu str\uuu()
。它回来了
<peewee.MySQLDatabase object at 0x7f4d6a996198>
我认为对于MySQL数据库,您可以这样做:
for data in foo_data:
for k,v in data.items():
if (Foo.select(Foo.bar).where(Foo.bar == v).count()) == 0:
Foo.insert(bar=v).execute()
因此,这可以是:
if 'SqliteDatabase' in db.__str__():
Foo.insert_many(foo_data).on_conflict(action='IGNORE').execute()
elif 'MySQLDatabase' in db.__str__():
with db.atomic():
for data in foo_data:
for k, v in data.items():
if (Foo.select(Foo.bar).where(Foo.bar == v).count()) == 0:
Foo.insert(bar=v).execute()
使用db.\uu str\uuu()
。它回来了
<peewee.MySQLDatabase object at 0x7f4d6a996198>
我认为对于MySQL数据库,您可以这样做:
for data in foo_data:
for k,v in data.items():
if (Foo.select(Foo.bar).where(Foo.bar == v).count()) == 0:
Foo.insert(bar=v).execute()
因此,这可以是:
if 'SqliteDatabase' in db.__str__():
Foo.insert_many(foo_data).on_conflict(action='IGNORE').execute()
elif 'MySQLDatabase' in db.__str__():
with db.atomic():
for data in foo_data:
for k, v in data.items():
if (Foo.select(Foo.bar).where(Foo.bar == v).count()) == 0:
Foo.insert(bar=v).execute()