Flask-sqlalchemy创建多列独立列的多列独立列
我在烧瓶项目中有一个模型:
class Location(db.Model):
__tablename__ = 'location'
id = db.Column(db.Integer, primary_key=True)
longitude = db.Column(db.Float, nullable=False)
latitude = db.Column(db.Float, nullable=False)
address_1 = db.Column(db.String(50))
address_2 = db.Column(db.String(8))
country_id = db.Column(db.Integer, db.ForeignKey('country.id', ondelete='SET NULL'))
city_id = db.Column(db.Integer, db.ForeignKey('city.id', ondelete='SET NULL'))
我需要通过对除ID
以外的所有列应用唯一约束来确保位置的唯一性。我已经尝试了这个:
__table_args__ = (
db.UniqueConstraint(
longitude,
latitude,
address_1,
address_2,
country_id,
city_id,
name="unique_loc"),
)
...但是,由于可取消的addresp_1','adversion_2'(在更多详细信息中)。我已经进行了一些调查,发现可能解决方案:
CREATE UNIQUE INDEX unique_loc ON location
(longitude, latitude, COALESCE(address_1, ''), COALESCE(address_2, ''), country_id, city_id);
是否可以通过ORM或RAW查询编写此约束?我使用的数据库 - Postgres 13。任何帮助将不胜感激。
I have a model in my flask project:
class Location(db.Model):
__tablename__ = 'location'
id = db.Column(db.Integer, primary_key=True)
longitude = db.Column(db.Float, nullable=False)
latitude = db.Column(db.Float, nullable=False)
address_1 = db.Column(db.String(50))
address_2 = db.Column(db.String(8))
country_id = db.Column(db.Integer, db.ForeignKey('country.id', ondelete='SET NULL'))
city_id = db.Column(db.Integer, db.ForeignKey('city.id', ondelete='SET NULL'))
I need to ensure uniqueness of location via applying unique constraint on all columns except an id
. I've tried this one:
__table_args__ = (
db.UniqueConstraint(
longitude,
latitude,
address_1,
address_2,
country_id,
city_id,
name="unique_loc"),
)
... but I still can save duplicates because of nullable `address_1', 'address_2' (in more details). I've investigated a bit and found a possible solution:
CREATE UNIQUE INDEX unique_loc ON location
(longitude, latitude, COALESCE(address_1, ''), COALESCE(address_2, ''), country_id, city_id);
Is it possible to write this constraint either via ORM or raw query? The database I use - postgres 13. Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
index
(带有unique = true
选项)和func.coalesce
:You can use
Index
(withunique=True
option) andfunc.coalesce
:因此,我发现了如何使用RAW查询创建索引。您所需要的只是用
flask db迁移生成新的迁移
,并修改def升级()
和'def defalgrade“:So, I've found out how to create an index with raw query. All you need is generate new migration with
flask db migrate
and modify bothdef upgrade()
and 'def downgrade`: