Doubt in the usage of bulk_create with update_conflicts=True

So I’m currently facing an issue where I’m supposed to create or update in bulk a few records. Thus I added unique constraints to my model and tried implementing a bulk_create with update_conflicts as True. But even when it faces an issue with inserting due to Unique constraints, it is not updating it.

My model:

class EventAttendance(db.SoftDeleteWithBaseModel):
    """
    Store the assessment report of the trainee
    """

    sub_batch = models.ForeignKey(
        "hubble.SubBatch", on_delete=models.CASCADE, related_name="event_attendance"
    )
    batch = models.ForeignKey(
        "hubble.Batch", on_delete=models.CASCADE, related_name="event_attendance"
    )
    event = models.ForeignKey("hubble.Event", on_delete=models.CASCADE, related_name="event_type")
    user = models.ForeignKey(
        "hubble.User", on_delete=models.CASCADE, related_name="event_attendance"
    )
    updated_by = models.ForeignKey(
        "hubble.User", on_delete=models.CASCADE, related_name="updated_event_attendance", null=True
    )
    present_status = models.BooleanField(default=False, verbose_name="Present status")
    trainee_arrival_time = models.TimeField(null=True)

    class Meta:
        """
        Meta class for defining class behavior and properties.
        """

        db_table = "event_attendance"
        constraints = [
            models.UniqueConstraint(
                fields=["user", "event", "deleted_at"],
                name="unique trainee attendance with soft delete",
            ),
            models.UniqueConstraint(
                fields=["user", "event"],
                name="unique trainee attendance",
                condition=db.models.Q(deleted_at__isnull=True),
            ),
        ]

My logic to either create or update:

def bulk_create_event_attendance(batch, user_ids, request_user, event, data_frame):
    """
    Used to bulk update the attendance for an event.
    """
    attendance_instances_to_be_created_or_updated = []
    for row in range(len(data_frame)):
        attendance_instances_to_be_created_or_updated.append(
            EventAttendance(
                batch=batch,
                user_id=user_ids[row]["id"],
                sub_batch_id=user_ids[row]["intern_details__sub_batch_id"],
                event=event,
                trainee_arrival_time=data_frame["Time"][row],
                present_status=data_frame["Present Status"][row].lower() == "yes",
                updated_by=request_user,
                updated_at=timezone.now(),
            )
        )
    EventAttendance.objects.bulk_create(
        attendance_instances_to_be_created_or_updated,
        update_conflicts=True,
        update_fields=["present_status", "trainee_arrival_time", "updated_at", "updated_by"],
        unique_fields=["user", "event", "deleted_at"],
    )

Error raised:
duplicate key value violates unique constraint “unique trainee attendance”
DETAIL: Key (user_id, event_id)=(273, 1) already exists.

Can someone help me to fix this issue?

1 Like

There was a change to behavior on update_conflicts in django 5.0. Not sure if this would affect your outcome but have a look.

I have the same problem, any update about it

Well this happens when there are multiple objects in with the same values in the initial array.
In this case, you must have two EventAttendance with user_id=273 and event_id = 1 in
attendance_instances_to_be_created_or_updated. In order to work, it should be ONLY ONE!