Reputation: 6693
I want to query 'one movie is played by which theaters?'
I have a model here:
class Movie(models.Model):
link = models.URLField()
title = models.CharField(max_length=255, null=True)
class MovieTheater(models.Model):
movietheater = models.ManyToManyField(Movie,null=True,blank=True,through="MovieShowtime")
movie_theater = models.CharField(max_length=255, null=True)
city = models.CharField(max_length=255, null=True) #east west north south
class MovieShowtime(models.Model):
theater = models.ForeignKey( MovieTheater, null=True,blank=True,related_name = 'theater' )
movie = models.ForeignKey( Movie, null=True,blank=True,related_name = 'movie' )
time = models.TextField(null=True,blank=True)
if I use this shell:
I will get all the MovieShowtime
objects
obj = Movie.objects.get(link='www.test.com')
obj.movie.all()
BUT the MovieShowtime
objects is belong to many MovieTheater
so when I print this out , it will get a lot of duplicate theater_id
for i in obj.movie.all():
print i.theater_id
69
69
78
78
78
76
76
75
83
How can I only get 69 ,78, 76,75,83 without duplicate,so that I can know this movie is played in which theaters
or is there a method I can get the movie_theater name(field:movie_theater
) not the theater_id directly??
like :
'AMC'
'FOX'
'BLABLABLA'
I try to figure it out for a while,still have no idea. Please guide me thank you very much.
Upvotes: 0
Views: 155
Reputation: 5048
you should carefully read the documentation, your case is possibly exactly the one in the example, so you would end up with a query like:
mt_names = [mt.name for mt in MovieTheater.objects.filter(movietheater__link="www.test.com")]
Upvotes: 0
Reputation: 1483
Django provides the ability to avoid duplicates with the distinct()
functionality.
https://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct
Django also provides the ability to only return the fields necessary by using the values()
functionality.
https://docs.djangoproject.com/en/dev/ref/models/querysets/#values
Combining these two should give you the functionality you are looking for.
To return distinct theater ids...
for i in obj.movie.all().values('theater').distinct():
print i['theater']
To return distinct theater names...
for i in obj.movie.all().values('theater__movie_theater').distinct():
print i['theater__movie_theater']
Upvotes: 1