Tuesday 15 April 2014

python - Django foreignkey query -



python - Django foreignkey query -

i have model allmovie save name of movie, allmovietheater save theaters playing movie, , allmovieshowtime save playing time in theatre

class allmovie(models.model): link = models.urlfield() title = models.charfield(max_length=100, null=true) releaseday = models.charfield(max_length=100, null=true) def __unicode__(self): homecoming '%s' % (self.title) class allmovietheater(models.model): allmovietheater = models.foreignkey(allmovie,null=true,blank=true) movie_theater = models.charfield(max_length=255, null=true) def __unicode__(self): homecoming '%s' % (self.movie_theater) class allmovieshowtime(models.model): theatre = models.foreignkey( allmovietheater, null=true,blank=true,related_name = 'theater' ) film = models.foreignkey( allmovie, null=true,blank=true,related_name = 'movie' ) time = models.charfield(max_length=100, null=true) def __unicode__(self): homecoming '%s' % (self.time)

for example: film 'abc' in theaters super theatre , man theater want know showtime in super theater

movie | theatre | showtime abc super theatre 8:00 9:30 film | theatre | showtime abc man theatre 8:00 10:00

but donn't know how query it. , query has error:

>>>obj = allmovie.objects.get(title='abc') <allmovie: abc> >>>obj2 = allmovietheater_set.filter(movie_theater=’super theater') [<allmovietheater: super theater> >>>obj3 = obj2.theater_set.all() attributeerror: 'queryset' object has no attribute 'theater_set'

please teach me give thanks you

a film can played in many theaters, , theatre shows many movies. relationship between "movie" model , "theater" model should many-to-many relationship, , "showtime" intermediate model used rule 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): homecoming '%s' % (self.title) class theater(models.model): movies = models.manytomanyfield(movie, null=true, blank=true, through="showtime") theatre = models.charfield(max_length=255, null=true) def __unicode__(self): homecoming '%s' % (self.movie_theater) class showtime(models.model): theatre = models.foreignkey(theater, null=true, blank=true) film = models.foreignkey(movie, null=true, blank=true) time = models.charfield(max_length=100, null=true) def __unicode__(self): homecoming '%s' % (self.time)

to know showtime of film "abc" in theatre "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'

python django

No comments:

Post a Comment