ApPeL
ApPeL

Reputation: 4921

Django update multiple queries

I am building a small app that looks at availability of vehicles and helps a customer book it.

in this I am making use of a form wizard that guides the user through the steps.

in the backend I am updating all the queries successfully, however I am not quite sure on how to execute one part of it.

I have two models, Quote and Vehicle

Vehicle is_bok = True or False Quote looks at the vehicle is_booked=False

When the user generates his quote he can see how many vehicles are available ie, 5.

if I then choose 2 vehicles, I would like to update the first two available vehicles to is_booked=True

### Check the vehicle availability and deduct amount of vehicles booked
        amount_of_vehicles = 2
        vehicle = Vehicle.objects.filter(is_booked=False)
        ### run update for each vehicle
        vehicle.update()

How would I achieve this?

Upvotes: 0

Views: 661

Answers (1)

Marcis
Marcis

Reputation: 4617

EDIT. You have to run update query for each element in queryset because of slice (limit):

amount_of_vehicles = 2
vehicles = Vehicle.objects.filter(is_booked=False)[0:amount_of_vehicles]
for vehicle in vehicles:
  vehicle.is_booked = True
  vehicle.save()

Upvotes: 2

Related Questions