如何在Peewee的get_or_create中忽略url列,基于name和industry判断重复?
Peewee get_or_create 忽略指定列实现方案
Peewee 的 get_or_create 本身没有专门的参数让你直接忽略某列,但你可以通过明确指定仅用 name 和 industry 作为查询判定条件,来实现你的需求——只检查这两个字段是否存在,存在则返回现有记录,不存在则新增条目(包含 url 字段)。
具体实现步骤
核心思路是把需要用来判断重复的字段(name、industry)作为 get_or_create 的查询条件,将可能变更的 url 放在 defaults 参数里(或者在新增时赋值):
- 先假设你的模型定义如下:
from peewee import Model, CharField, IntegerField, SqliteDatabase db = SqliteDatabase('your_db.db') class YourModel(Model): id = IntegerField(primary_key=True) name = CharField() industry = CharField() url = CharField(null=True) class Meta: database = db
- 使用
get_or_create时的正确写法:
# 仅用这两个字段判断记录是否存在 lookup_conditions = {'name': '测试名称', 'industry': '互联网'} # 新增时要设置的 url 值 new_url = 'https://new-example.com' # 执行查询/创建操作 instance, is_created = YourModel.get_or_create(**lookup_conditions, defaults={'url': new_url}) # 如果需要在记录已存在时更新 url,可添加以下逻辑 if not is_created: if instance.url != new_url: instance.url = new_url instance.save()
关键说明
lookup_conditions里的字段是 Peewee 用来匹配记录的唯一依据,完全不会涉及 url 字段,刚好满足你忽略 url 检查的需求。defaults里的字段仅在新增记录时生效,如果记录已存在,不会自动覆盖现有值。如果需要同步更新 url,就像上面代码那样手动判断并保存即可。- 虽然没有设置联合唯一约束,但这种方式依然能实现按 name+industry 去重的逻辑。不过如果是高并发场景,建议加个事务或者数据库层面的锁,避免竞态条件导致重复插入。
内容的提问来源于stack exchange,提问作者cynthia
相关产品推荐
相关产品推荐

