Django:IntegrityError重复键值违反唯一约束“ ride_ownerrequest_driver_id_key”详细信息:键(driver_id)=(2)已存在

时间:2019-02-07 03:56:26

标签: django django-models django-forms django-templates django-views

这里我有三种型号: 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)

车辆

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)

用户

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)

我的问题发生在:

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')

有人可以给些提示吗?谢谢!

1 个答案:

答案 0 :(得分:0)

您具有从OneToOneOwnerRequest的{​​{1}}关系。这意味着您只能查看一个。

在您的代码中,何时:

User

如果驱动程序已经与另一个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. 实例相关,它将对此抱怨。

也许您应该考虑与用户OwnerRequest建立这种关系。