Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8692945
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T00:25:46+00:00 2026-06-13T00:25:46+00:00

I am having issues figuring out MySQL INSERT … ON DUPLICATE KEY UPDATE with

  • 0

I am having issues figuring out MySQL INSERT … ON DUPLICATE KEY UPDATE with django 1.4.

The table that I am trying to insert records has a 2 column(composite) unique key. Records that I am receiving is from a 3rd party source and values will change over time except for those fields that makes the unique key set. I am receiving 1 ~ 5k records at a time, and would need to

Currently I am using Model.objects.bulk_create to bulk insert, performance is really amazing as it issues generally one query no matter how big the record set is. However, as my records can change over time on the 3rd party end, I need to perform the MySQL INSERT … ON DUPLICATE KEY UPDATE query on the recordset.

I am planning to write raw SQL statements and execute using something like here:

sql = "MySQL INSERT ... ON DUPLICATE KEY UPDATE"

raw_insert(sql)

def raw_insert(sql):
    from django.db import connection, transaction
    cursor = connection.cursor()

    # Data modifying operation - commit required
    cursor.execute(sql)
    transaction.commit_unless_managed()

    return 1

Wondering if there is a better solution to my problem. Also how would I sanitize the field values for raw insert?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T00:25:47+00:00Added an answer on June 13, 2026 at 12:25 am

    So I created a custom manager. Here is the manager:

    class BulkInsertManager(models.Manager):
        def _bulk_insert_or_update(self, create_fields, update_fields, values):
    
            from django.db import connection, transaction
            cursor = connection.cursor()
    
            db_table = self.model._meta.db_table
    
            values_sql = []
            values_data =[]
    
            for value_lists in values:
                values_sql.append( "(%s)" % (','.join([ "%s" for i in range(len(value_lists))]),) )
                values_data.extend(value_lists)
    
            base_sql = "INSERT INTO %s (%s) VALUES " % (db_table, ",".join(create_fields))
    
            on_duplicates = []
    
            for field in update_fields:
                on_duplicates.append(field + "=VALUES(" + field +")")
    
            sql = "%s %s ON DUPLICATE KEY UPDATE %s" % (base_sql, ", ".join(values_sql), ",".join(on_duplicates))
    
            cursor.executemany(sql, [values_data])
            transaction.commit_unless_managed()
    

    And a sample model:

    class User_Friend(models.Model):
        objects = BulkInsertManager() # assign a custom manager to handle bulk insert
    
        id = models.CharField(max_length=255)
        user = models.ForeignKey(User, null=False, blank=False)
        first_name = models.CharField(max_length=30)
        last_name = models.CharField(max_length=30)
        city = models.CharField(max_length=50, null=True, blank=True)
        province = models.CharField(max_length=50, null=True, blank=True)
        country =  models.CharField(max_length=30, null=True, blank=True)
    

    And sample implementation:

    def save_user_friends(user, friends):
        user_friends = []
        for friend in friends:
    
            create_fields = ['id', 'user_id', 'first_name', 'last_name', 'city', 'province', 'country']
            update_fields = ['first_name', 'last_name', 'city', 'province', 'country']
    
            user_friends.append(
                [
                    str(user.id), 
                    str(friend['id']),
                    friend['first_name'],
                    friend['last_name'],
                    friend['city'],
                    friend['province'],
                    friend['country'],
                ]
            )
    
        User_Friend.objects._bulk_insert_or_update(create_fields, update_fields, user_friends)
    

    Here is the gist.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm very new to Tomcat and I'm having some issues figuring out how to
I am having some problems figuring out this issue. I have a server that
I am having issues figuring out if this is possible. Any pointers would be
I am having issues figuring out how to sort a large data set into
I'm having issues figuring out how to programmatically upload synonyms to the google search
I am having issues figuring out what this issue is. I have googled around
I am having issues figuring out how to do this. This isnt the real
I am having issues figuring out why I'm getting a nullpointerexception thrown. It doesn't
I am having issues figuring out how to split on multiple delimiters using regular
I'm having issues figuring out where it's grabbing the default value. I tried changing

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.