如何将Raw Sql查询转换为Django模型

时间:2016-12-19 14:50:03

标签: python django sqlite django-models django-queryset

我的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。

提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以使用ManyToManyField

来实现这一目标

只需要两个步骤:

  1. ManyToManyField创建movieActiveDays个字段TheaterShowTimings
  2. 使用新的movieActiveDays字段进行查询。
  3. 模型定义
    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()