Home > Software engineering >  Django ORM better way to manipulate django ORM query
Django ORM better way to manipulate django ORM query

Time:11-06

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)

CodePudding user response:

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.

  • Related