When trying to bulk_create with update_conflicts=True and a UniqueConstraint on the model, I get duplicate entries.
Here’s the model:
class TripSamsara(models.Model):
driver_1 = models.ForeignKey(Driver, on_delete=models.CASCADE, related_name='driver_1_trips_samsara', null=True, blank=True)
driver_2 = models.ForeignKey(Driver, on_delete=models.CASCADE, related_name='driver_2_trips_samsara', null=True, blank=True)
truck = models.ForeignKey(Truck, on_delete=models.CASCADE, null=True)
trailer = models.ForeignKey(Trailer, on_delete=models.CASCADE, null=True)
start_location = models.CharField(max_length=255, null=True, blank=True)
end_location = models.CharField(max_length=255, null=True, blank=True)
start_date = models.DateTimeField(null=True, blank=True)
end_date = models.DateTimeField(null=True, blank=True)
distance_meters = models.IntegerField(null=True, blank=True)
fuel_consumed_ml = models.IntegerField(null=True, blank=True)
start_odometer = models.IntegerField(null=True, blank=True)
end_odometer = models.IntegerField(null=True, blank=True)
class Meta:
verbose_name_plural = 'Trips Samsara'
constraints = [
models.UniqueConstraint(fields=['driver_1', 'driver_2', 'truck', 'start_odometer', 'end_odometer'], name='unique_trip_samsara')
]
Here’s the function:
samsara_created_trips = TripSamsara.objects.bulk_create(
trips_bulk_create,
update_conflicts=True,
unique_fields=['driver_1', 'driver_2', 'truck', 'start_odometer', 'end_odometer'],
update_fields=['trailer', 'start_location', 'end_location', 'distance_meters', 'fuel_consumed_ml', 'start_date', 'end_date']
)
The db table seems to have the unique constraint as well:
What am I missing?