To perform a Django mySQL database insert query with a composite primary key using .save() and .validate_unique, follow these steps:
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')
my_instance = MyModel(id1=1, id2='example', field1='value1', field2='value2')
my_instance.save()
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.
Asked: 2022-10-19 11:00:00 +0000
Seen: 12 times
Last updated: Jul 11 '21