我有一个 CarRent 模型,它是 Car 模型的外键,付款后在 CarRent detailView 上我想更改 CarRent 模型和 Car 模型,代码适用于 CarRent 模型,但更改 Car模型导致“AttributeError at /car/requests/4/ 类型对象“汽车”没有属性“对象””错误
class Car(models.Model):
car_owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='car_owner', on_delete=models.CASCADE)
car_model = models.CharField(max_length=20, blank=True, null=True)
rented = models.BooleanField(default=False)
class CarRent(models.Model):
car = models.ForeignKey(Car, related_name='rented_car', on_delete=models.CASCADE)
driver = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='driver_renting', on_delete=models.CASCADE)
active_rent = models.BooleanField(default=False, null=True)
rent_paid = models.BooleanField(default=False)
@login_required
@driver_required(redirect_field_name='app:home')
@csrf_protect
def car_rent_detail_view(request, pk):
object = get_object_or_404(CarRent, id=pk)
# queryset = Car.objects.get(id=pk)
car_object = get_object_or_404(queryset, id=pk)
paystack = PaystackAccount(
settings.PAYSTACK_EMAIL,
settings.PAYSTACK_PUBLIC_KEY,
object.total_cost
)
context = {'object': object, 'pk_public': settings.PAYSTACK_PUBLIC_KEY, 'currency': 'NGN', 'paystack': paystack,
}
if request.method == 'POST':
if paystack.verify_transaction(request.POST['reference']):
messages.success(request, "paystack payment successfull")
car_rented = Car.object.get(pk=pk)
car_rented.rented = True
rent_activation = CarRent.objects.get(pk=pk)
rent_activation.active_rent = True
rent_activation.rent_paid = True
rent_activation.save()
messages.success(request, "Your Rent has successfully being updated")
return render(request, 'app/CarRent_detail.html', context=context)
任何帮助将不胜感激。
答案 0 :(得分:0)
这是一个错字,您需要使用 objects
来访问管理器方法,而不是对象。所以替换:
car_rented = Car.object.get(pk=pk)
^^^^^^
与:
car_rented = Car.objects.get(rented_car__pk=pk)
您可以通过 related_name
(即 'rented_car')将查询从汽车模型反向查询到 CarRent。可以在 documentation 中找到更多信息。