Q:

Django: IntegrityError duplicate key value violates unique constraint "ride_ownerrequest_driver_id_key" DETAIL: Key (driver_id)=(2) already exists

Here I have three models:
OwnerRequest:
class OwnerRequest(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='owner_owner_request_set')

    driver = models.OneToOneField(User, on_delete=models.CASCADE, related_name='driver_owner_request_set', blank=True, null=True)

and 
Vehicle
class Vehicle(models.Model):
    plate_number = models.CharField(max_length=10, primary_key=True, blank=False, null=False)
    driver = models.OneToOneField(User, on_delete=models.CASCADE, blank=False, null=False)

and 
User
class User(AbstractUser):
    ROLE = Choices('owner', 'driver', 'sharer')
    catalog = models.CharField(max_length=6, choices=ROLE, blank=True, null=True)
    plate_number = models.CharField(max_length=10, blank=True, null=True)

and my problem happens at:
def driver_confirm_request(request, pk):
    to_confirm = get_object_or_404(OwnerRequest, pk=pk)
    driver = get_object_or_404(User, pk=request.user.id)
    if to_confirm.status == 'confirmed':
        messages.info(request, "You are slow!")
        return redirect('ride:home')
    if driver != request.user:
        return redirect('ride:home')
    to_confirm.driver = driver
    to_confirm.status = 'confirmed'
    to_confirm.save() # HAPPENS HERE
    messages.info(request, "Ride Confirmed!")
    return redirect('ride:home')

Could anyone give some hint? Thanks!

A:

You have a OneToOne relationship from OwnerRequest to User. That means you can have only one, in your view, you have to check that.
In your code when:
if driver != request.user:
        return redirect('ride:home')
    to_confirm.driver = driver
    to_confirm.status = 'confirmed'
    to_confirm.save() # If driver is already related, this will fail.

if a driver is already related to another OwnerRequest instance it will complain about that.
Perhaps you should consider to user ManyToManyField for that relationship.

