我的models.py:
class TheaterShowTimings(models.Model):
showname = models.CharField(max_length=100)
showtime = models.TimeField() # stores only time
theatershowtimingsid = models.CharField(primary_key=True, max_length=100)
def __str__(self):
return self.theatershowtimingsid
class MovieActiveDays(models.Model):
date = models.DateField() # stores single only date
moviedetails = models.ForeignKey(MovieDetails, on_delete=models.CASCADE)
theaterbase = models.ForeignKey(TheaterBase, on_delete=models.CASCADE)
activedayid = models.CharField(primary_key=True, max_length=100)
def __str__(self):
return self.activedayid
class ActiveShowTimings(models.Model):
TheaterShowTimings = models.ForeignKey(TheaterShowTimings, on_delete=models.CASCADE)
MovieActiveDays = models.ForeignKey(MovieActiveDays, on_delete=models.CASCADE)
activeshowid = models.CharField(primary_key=True, max_length=100)
def __str__(self):
return self.activeshowid
我的views.py:
show_name_list = TheaterShowTimings.objects.raw('SELECT distinct * FROM Book_TheaterShowTimings where theatershowtimingsid IN (select TheaterShowTimings_id from Book_ActiveShowTimings where MovieActiveDays_id IN (select activedayid from Book_MovieActiveDays where date = "2016-12-19")) order by showtime ASC')
views.py 中的上述查询正常正常。但是,我想将其转换为django查询集。请帮助我,我坚持将原始sql查询转换为queryset。
提前致谢。
答案 0 :(得分:1)
您可以使用ManyToManyField
。
只需要两个步骤:
ManyToManyField
创建movieActiveDays
个字段TheaterShowTimings
。movieActiveDays
字段进行查询。class TheaterShowTimings(models.Model):
showname = models.CharField(max_length=100)
showtime = models.TimeField() # stores only time
theatershowtimingsid = models.CharField(primary_key=True, max_length=100)
# many to many fields to MovieActiveDays
movieActiveDays = models.ManyToManyField('MovieActiveDays', through='ActiveShowTimings')
def __str__(self):
return self.theatershowtimingsid
查询:
TheaterShowTimings.objects.filter(movieActiveDays__date='2016-12-19').distinct()