I want to know how to do bulk REPLACE in Django.

Asked 2 years ago, Updated 2 years ago, 81 views

If you know how to run MySQL bulk REPLACE using Python Django's model manager, please let me know.

class SpamModel (models.Model):
    ...

SpamModel.objects.bulk_create([]
    SpamModel (**item) for item in items])

We are doing bulk insert like this, but we would like to do REPLACE instead of INSERT here.

This is the image.

SpamModel.objects.bulk_create([[]
    SpamModel(**item) for item items], mysql_replace=True)

I don't think I can use this code.

REPLACE INTO spam_spammodel(a,b)VALUES(...),(...),(...),(...),...

I expect this kind of SQL to come out

U Not UPSERT.Also, it is not INSERT since DELETE.I just want to run mySQL REPLACE statement.

python mysql django

2022-09-30 19:53

1 Answers

The purpose is to change the SpamModel.somefield to "z" in the case of "X", I think you can use .update():

SpamModel.objects.filter(somefield='x') .update(somefield='z')

REPLACE works exactly like INSERT, except that if an old row in the
table has the same value as a new row for a PRIMARY KEY or a UNIQUE
index, the old row is deleted before the new row is inserted.

Note:
REPLACE makes sense only if a table has a PRIMARY KEY or UNIQUE
index.Otherwise, it becomes equal to INSERT, because there is no
index to be used to determine which a new row duplicates another.

https://dev.mysql.com/doc/refman/5.0/en/replace.html

Then, if you want to make it happen with Django, I think it will be INSERT after DELETE.If not, do you only have to issue your own SQL statement?

https://docs.djangoproject.com/en/1.8/topics/db/sql/ #executing-custom-sql-directly


2022-09-30 19:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.