Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To perform a Django mySQL database insert query with a composite primary key using .save() and .validate_unique, follow these steps:

  1. Define the model for the table you want to insert data into, including the composite primary key. For example:
class MyModel(models.Model):
    id1 = models.IntegerField()
    id2 = models.CharField(max_length=50)
    field1 = models.CharField(max_length=100)
    field2 = models.CharField(max_length=100)

    class Meta:
        unique_together = ('id1', 'id2')
  1. Create an instance of the model with the data you want to insert, and call the .save() method on it. This will attempt to insert the data into the database.
my_instance = MyModel(id1=1, id2='example', field1='value1', field2='value2')
my_instance.save()
  1. If the .save() method raises a IntegrityError due to a duplicate key error, catch the error and call the .validateunique() method on the instance. This method checks if the uniquetogether constraint is violated, and raises a ValidationError if it is.
from django.db import IntegrityError, transaction
from django.core.exceptions import ValidationError

try:
    with transaction.atomic():
        my_instance.save()
except IntegrityError as e:
    transaction.rollback()
    if 'unique constraint' in str(e).lower():
        try:
            my_instance.validate_unique()
        except ValidationError as e:
            # handle the validation error
            pass
    else:
        # handle other types of integrity error
        pass

Note that you should always use transactions when inserting data into a database, to ensure data consistency in case of errors.