0๐
I had a similar situation. My model fields allowed me to use this hacky solution. It worked.
class Concept(models.Model):
a = models.CharField(max_length=255)
b = models.CharField(max_length=255)
c = models.CharField(max_length=255)
d = models.CharField(max_length=255)
_a_b = models.CharField(max_length=255, editable=False, unique=True)
def save(self, *args, **kwargs):
# Not that this won't be helpful when doing a bulk_create so you will
# have to set this value when creating the bulk_create objects
self._a_b = f"{self.a}{self.b}"
super().save(*args, **kwargs)
class Meta:
constraints = [
models.UniqueConstraint(fields=('a', 'b'),name='a_b_constraint'),
]
Concept.objects.bulk_create(
concepts, # make sure to create _a_b in the loop that create this
update_conflicts=True,
update_fields=('c','d',),
unique_fields=('_a_b',)
)
๐คEric O.
Source:stackexchange.com