Django嵌套查询

时间:2018-01-07 14:14:12

标签: django python-3.x mariadb

在Django中,我试图在不使用原始查询的情况下实现这样的嵌套SQL结构:

SELECT id, 
   session_hash, 
   user_id, 
   price_type_id, 
   room_category_id, 
   check_in_date, 
   price, 
   captured_date 
FROM   (SELECT p.*, 
           Row_number() OVER (partition BY check_in_date, price_type_id, room_category_id ORDER BY captured_date DESC) AS rn 
    FROM   dashboard_prices p 
    WHERE  room_category_id = 1 
           AND price_type_id = 1 
           AND check_in_date >= '2018-01-01 00:00:00' 
           AND check_in_date <= '2018-01-02 00:00:00') p 
WHERE  rn = 1

我无法通过使用&#34; normal&#34;来弄清楚如何实现这一目标。 Django中的查询表达式。

型号:

class Prices(models.Model):
    session_hash = models.CharField(max_length=32, blank=False, null=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, null=False)
    price_type = models.ForeignKey(PriceTypes, on_delete=models.CASCADE, blank=False, null=False)
    room_category = models.ForeignKey(RoomCategories, on_delete=models.CASCADE, blank=False, null=False)
    check_in_date = models.DateTimeField(blank=False, null=False, db_index=True)
    price = models.IntegerField(blank=False, null=False)
    captured_date = models.DateTimeField(default=timezone.now, blank=True)

    row_number = 'row_number() OVER (PARTITION BY check_in_date, price_type_id, room_category_id ' \
             'ORDER BY captured_date DESC)'

我已经实现了通过以下方式运行内部查询:

price = Prices.objects.annotate(rn=RawSQL(Prices.row_number[]))
    .filter(room_category_id=req['room_category_id'], price_type_id=req['price_type_id'],
            check_in_date__gte=check_in_date, check_in_date__lte=check_out_date)

但是在此之后过滤只会带来错误:

django.db.utils.DatabaseError: Window function is allowed only in SELECT list and ORDER BY clause

添加时:     

.filter(rn=1)

是否有可能实现这一目标?

谢谢!

0 个答案:

没有答案