Django模型查询许多字段

2024-09-29 01:34:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想问“哪个影院播放一部电影?”你知道吗

我这里有一个模型:

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)而不是电影院id??
比如:

'AMC'
'FOX'
'BLABLABLA'

我想了一会儿,还是不知道。 请引导我非常感谢。你知道吗


Tags: trueobjmodelmodelsmovienulllengthmax
2条回答

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

您应该仔细阅读documentation,您的案例可能正是示例中的案例,因此您将得到如下查询:

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

相关问题 更多 >