2014-12-19 102 views
0

我想查詢'一部電影是由哪個劇院播放?'django模式查詢ManyToMany字段

我這裏有一個模型:

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)    

,如果我用這個殼: 我會得到所有的MovieShowtime對象

obj = Movie.objects.get(link='www.test.com') 
obj.movie.all() 

MovieShowtime對象是屬於許多MovieTheater 所以當我打印出來,它會得到很多重複的劇院_id

for i in obj.movie.all(): 
    print i.theater_id 

69 
69 
78 
78 
78 
76 
76 
75 
83 

我怎麼只能拿到69,78,76,75,83沒有重複的,這樣我可以知道這部電影播放在電影院
還是有方法,我可以得到movie_theater名(現場:movie_theater )不是theatre_id直接??
喜歡:

'AMC' 
'FOX' 
'BLABLABLA' 

我揣摩了一會兒,還是不知道。 請引導我非常感謝你。

回答

1

Django提供了避免與distinct()功能重複的功能。 https://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct

Django還提供了僅返回使用values()功能所需的字段的功能。 https://docs.djangoproject.com/en/dev/ref/models/querysets/#values

結合這兩個應該給你你正在尋找的功能。

要返回不同的影院IDS ...

for i in obj.movie.all().values('theater').distinct(): 
    print i['theater'] 

要返回不同的影院名稱...

for i in obj.movie.all().values('theater__movie_theater').distinct(): 
    print i['theater__movie_theater'] 
0

您應仔細閱讀documentation,你的情況可能是完全一個在例如,所以你最終會得到如下查詢:

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