1

Below are the models:

class Seat(models.Model):
    hall = models.ForeignKey(Hall,on_delete=CASCADE)
    type = models.TextField(verbose_name="Seat Type")

class Show(models.Model):
    show_time = models.TimeField(verbose_name='Show Time')
    movie = models.ForeignKey(Movie,on_delete=CASCADE)
    hall = models.ForeignKey(Hall,on_delete=CASCADE)
    cinema = models.ForeignKey(Cinema,on_delete=CASCADE)

class Booking(models.Model):
    seat = models.ForeignKey(Seat,on_delete=CASCADE)
    show = models.ForeignKey(Show,on_delete=CASCADE)
    movie = models.ForeignKey(Movie,on_delete=CASCADE)
    hall = models.ForeignKey(Hall,on_delete=CASCADE)
    cinema = models.ForeignKey(Cinema,on_delete=CASCADE)
    user = models.ForeignKey(User, verbose_name="Username", on_delete=DO_NOTHING) # donothing

Explanation of the models:

Multiple Seats in a Hall

Each Hall hosts multiple Shows

Each Booking is basically a ticket for a show with a specific seat and a specific show.

Requirement is to get a queryset that has all seats not present in the bookings table for a specific show. Basically, get the list of available seats for a show by checking they are not present in the Bookings table

The SQL query would look like this:

SELECT * FROM Seat as S join Show as Sh on S.hall = Sh.hall join Bookings as B on B.show = Sh.id where Sh.id = 1 AND B.seat IS NULL

how to convert this to Django ORM:

able to do it like this (is there a better way rather than creating the seat_id_list?):

            qs = Seat.objects.filter(hall=hid) #----------------------------------
            show_bookings = Booking.objects.filter(show=spk)
            seat_id_list = []

            for each_booking in show_bookings:
                print(each_booking.seat.id)
                seat_id_list.append(each_booking.seat.id)
            qss = Seat.objects.exclude(id__in = seat_id_list)

1 Answer 1

1

You can obtain these Seats with:

Seat.objects.filter(hall=hid).exclude(booking__show=spk)

This will retrieve all Seats for a given Hall object hid where there is no Booking for a Show determined by the spk object.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, this worked well. What does booking represent here? it is not a field in the Seat model neither in the show model? also the model is called Booking.
@akashdeep: If you define a ForeignKey, Django defines a relation in reverse. By default it uses as related_query_name the name of the model where you define it in lowercase, so you can access the related bookings in a query with booking.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.