这里我有三种型号: 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')
有人可以给些提示吗?谢谢!
答案 0 :(得分:0)
您具有从OneToOne
到OwnerRequest
的{{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
建立这种关系。