[Answer]-Django foreignkey query

1👍

A movie can be played in many theaters, and a theater shows many movies. So the relationship between a “Movie” model and a “Theater” model should be many-to-many relationship, and the “ShowTime” is the intermediate model that will be used to govern this relationship.

class Movie(models.Model):
    link = models.URLField()
    title = models.CharField(max_length=100, null=True)
    releaseday = models.CharField(max_length=100, null=True)               
    def __unicode__(self):
        return '%s' % (self.title)

class Theater(models.Model):
    movies = models.ManyToManyField(Movie, null=True, blank=True, through="ShowTime")
    theater = models.CharField(max_length=255, null=True)     
    def __unicode__(self):
        return '%s' % (self.movie_theater)

class ShowTime(models.Model):
    theater = models.ForeignKey(Theater, null=True, blank=True)
    movie = models.ForeignKey(Movie, null=True, blank=True)
    time = models.CharField(max_length=100, null=True)
    def __unicode__(self):
        return '%s' % (self.time)

To know the showtime of the movie “ABC” in the theater “super”:

>>> ShowTime.objects.filter(theater__theater="super", movie__title="ABC")
[<ShowTime: ShowTime object>, <ShowTime: ShowTime object>]
>>> ShowTime.objects.filter(theater__theater="super", movie__title="ABC")[0].time
'8:00'
>>> ShowTime.objects.filter(theater__theater="super", movie__title="ABC")[1].time
'10:00'
👤neofoo

0👍

obj2 is a QuerySet object.

You should access elements of obj2 like any iterator.

For you situation, a possible way to get obj3 is:

obj3 = [x.theater_set.all() for x in obj2]
👤Rikka

0👍

have you tried something like :

AllMovieShowtime.objects.filter(movie__title="ABC",theater__movie_theater="super theater")

Leave a comment