'Django UNIQUE constraint fails with composite primary key
I have searched for similar cases but they do not seem to question the model.save() method. I am new to Django and, following the standard methodology, have declared a class to map it to a ddbb (autoincremental id):
class Crudos(models.Model):
cuenta = models.CharField(verbose_name='Cuenta', max_length=100)
concepto = models.CharField(verbose_name='Concepto', max_length=100, default='indefinido')
magnitud = models.FloatField(verbose_name='Magnitud')
fecha = models.DateField(verbose_name='Fecha')
documento = models.FilePathField(verbose_name='Documento')
class Meta:
unique_together = ('cuenta', 'fecha',)
The view that uses this class also populates the table:
for index, row in df.iterrows():
data = Crudos(cuenta=row.Cuenta, concepto=row.Concepto, magnitud=row.Magnitud, fecha=row.Fecha, documento=row.Documento)
data.save()
The dataframe is generated from a file and the process works without problems the first time. If I use the same file twice, then I get the error message of UNIQUE constrain failed. Models.save() should be an update instead of an insert when trying to insert a register with the same unique combination of values. It does so when the primary key is included in the data to save. The problem comes when there is a need for a composite primary key, as it is the case of the Crudo class, which is reflected by the unique_together condition. It seems Django is not able to interpret that condition as one to execute an update instead of an insert. As a way around that problem, the process works by:
for i, row in df.iterrows():
register = Crudos.objects.get(cuenta=row.Cuenta, fecha=row.Fecha)
if register:
data = Crudos(id=register.id, cuenta=row.Cuenta, concepto=row.Concepto, magnitud=row.Magnitud, fecha=row.Fecha, documento=row.Documento)
data.save()
else:
data = Crudos(cuenta=row.Cuenta, concepto=row.Concepto, magnitud=row.Magnitud, fecha=row.Fecha, documento=row.Documento)
data.save()
This process forces a query before each save, slowing down the process significantly. Is there some other more efficient alternative? Is there a better way that allows Django to automatically execute as an update situations that violate the UNIQUE condition?
Thanks
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
