簡體   English   中英

Django模型查詢ManyToMany字段

[英]django models query ManyToMany field

我想查詢“一部電影在哪些劇院上映?”

我在這里有一個模型:

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)              

如果使用此shell:我將獲得所有MovieShowtime對象

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

但是MovieShowtime對象屬於許多MovieTheater因此當我將其打印出來時,它將獲得很多重復的Theater_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名稱(field: movie_theater )而不是Theater_id?
喜歡 :

'AMC'
'FOX'
'BLABLABLA'

我試了一下,仍然不知道。 請指導我,非常感謝。

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

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

將兩者結合起來可以為您提供所需的功能。

要返回不同的劇院ID ...

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

您應該仔細閱讀文檔 ,您的案例可能恰好是示例中的案例,因此最終將得到如下查詢:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM