tortoise-orm icon indicating copy to clipboard operation
tortoise-orm copied to clipboard

How do ON DUPLICATE KEY UPDATE?

Open 16bc opened this issue 3 years ago • 3 comments

Table have a unique constrain on 2 fields. When i try to await MyModel.create(**dict_of_data) with exist entry in unique fields, i got error: tortoise.exceptions.IntegrityError: (1062, "Duplicate entry...

Try await MyModel(**dict_of_data).save(force_update=True) raise error: tortoise.exceptions.IntegrityError: Can't update object that doesn't exist. PK: None How can i do ON DUPLICATE KEY UPDATE for create new or update exist record without many requests and conditional structures?

16bc avatar Feb 15 '22 18:02 16bc

Try update_or_create or bulk_create

long2ice avatar Feb 16 '22 03:02 long2ice

Try update_or_create or bulk_create

update_or_create working not correct:

tortoise/models.py
[1090] instance = await cls.select_for_update().using_db(connection).get_or_none(**kwargs)

wrong return None instance and then later "Duplicate entry" exception init if any field in DB not equal new data. Does it matching all parameters, or only unique fields? I guess - all them, but why? Logically need only unique. I dont understand how it use. Why is there so much bureaucracy for such simple operation supported by database?

16bc avatar Feb 20 '22 14:02 16bc

Can we check by primary key's existence and then determine whether to create or update ?

Would check by primary key be better than check by the whole row data's identity for determine whether to create or update ?

jiangying000 avatar Apr 09 '24 15:04 jiangying000