django 在/vehicle/vehicle_view/ get()返回的多个对象返回了多个车辆-它返回了7

w7t8yxp5  于 2023-01-10  发布在  Go
关注(0)|答案(1)|浏览(143)

第一个月

如果我有多辆车,我希望向我显示保存在user_id数据库中的所有车辆

View.py 文件@login_required定义车辆_view(请求):

vehicle = get_object_or_404(Vehicle, user=request.user)
form = UpdateVehicleForm(request.POST or None, request.FILES or None,instance=vehicle)
context = {'form': form }
if request.method == 'POST':
   
        if form.is_valid():
            vehicle.save()
            messages.success(request, "Vehicle Updated!")
            return redirect('home')
        else:
            messages.error(request, "Invalid Data Provided")
return render(request, "user/edit_vehicle.html", context)

urls.py 路径('vehicle_view/',视图.车辆视图,名称='车辆视图'),
'

31moq8wy

31moq8wy1#

get_object_or_404(Vehicle,user = request. user)返回多个对象,则会根据具体情况引发此错误,如果不希望返回多个对象,则可以在代码中使用try except;如果需要多个对象,则可以使用filter方法。
示例:

try:
    vehicle = get_object_or_404(Vehicle, user=request.user)
except Vehicle.MultipleObjectsReturned:
    # Maybe do something.
    raise Http404

或使用过滤器:

vehicle = Vehicle.objects.filter(user=request.user)

相关问题