简体   繁体   中英

django models query ManyToMany field

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.

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']

您应该仔细阅读文档 ,您的案例可能恰好是示例中的案例,因此最终将得到如下查询:

mt_names = [mt.name for mt in MovieTheater.objects.filter(movietheater__link="www.test.com")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM