Given the following Model:
class Model1(models.Model):
m2mrelation = models.ManyToManyField('Model2', related_name='model2')
field1 = models.CharField(max_length=14)
data1 = models.FloatField()
data2 = models.FloatField()
data3 = models.FloatField()
data4 = models.FloatField()
data5 = models.FloatField()
field2 = models.CharField(max_length=10)
field3 = models.CharField(max_length=20)
class Meta:
indexes = [
models.Index(fields=['field1', 'field2', 'field3']),
]
unique_together = ['field1', 'field2', 'field3']
I’m trying to use the “get_or_create()” method to get or create a new Model1 inside a Model2 method:
for data in objects:
object, created = self.model1.get_or_create(
field1=field1,
field2=field2,
field3=field3,
defaults={
'data1': float(data[1]),
'data2': float(data[2]),
'data3': float(data[3]),
'data4': float(data[4]),
'data5': float(data[5])
}
)
if not object.m2mrelation.filter(id=self.id).exists():
object.m2mrelation.add(self)
When I’m trying to create new objects, I’m getting the IntegrityError: UNIQUE constraint failed
in the get_or_create
method.
Am I missing something?