【问题标题】:How to implement raw sql query in Tastypie如何在 Tastypie 中实现原始 sql 查询
【发布时间】:2014-12-10 21:32:05
【问题描述】:

我正在尝试执行这个简单的查询,但它不起作用。谢谢。

SELECT * FROM TSimple where (start_date < '2012-04-20' and end_date is null) or
  (end_date > '2012-04-20' and start_date < '2012-04-20')


class TSimple (models.Model):
  start_date = models.DateTimeField()
  end_date = models.DateTimeField(blank=True, null=True)
...



class TSimpleResource(ModelResource):
  def dehydrate(self, bundle):
    request_method = bundle.request.META['REQUEST_METHOD']

    if request_method=='GET':
      new_date = bundle.request.GET.get('new_date', '')
      qs = TSimple.objects.raw(
        'SELECT * FROM TSimple where (start_date<=\'' +
        new_date + '\' and end_date>=\'' +
        new_date + '\') or (start_date<=\'' + new_date +
        '\' and end_date is null)')

      ret_list = [row for row in qs]


      // NOT WORK. Not able to get correct json data in javascript. 
      // It needs return bundle. HOW to replace bundle?
      // Is this correct way to do it?
      return ret_list
    else:
      // This is ok.
      return bundle

我有以下问题:

1)(原始sql方法)如果在脱水方法中实现是正确的方法吗?如果是,则以上不起作用。它应该返回捆绑对象。如何构建新的bundle?

如果上述方法没问题,我注意到捆绑包已经使用默认查询(?)构造了 .data 字段,新查询将丢弃该字段。如果这是正确的做法,这就提出了问题。

2) 如果有其他原始的sql方法可以做到吗? sql在哪里执行?

3)如何在过滤器中做到这一点?

4) 我知道 sql 但不熟悉复杂的过滤器。这就是为什么我尝试使用原始 sql 方法来做快速原型。有什么退路?我注意到使用 Tastypie 有许多不必要的查询,我不知道如何摆脱它。例如,用外键查询表的数据触发查询另一个表的数据,我不想得到。

【问题讨论】:

    标签: tastypie


    【解决方案1】:

    我找出了过滤器,它似乎有效。但我仍然对原始 sql 感兴趣。

    def apply_filters(self, request, applicable_filters):
      base_filter = super(TSimpleResource, self).apply_filters(request,
                                                          applicable_filters)
    
      new_date = request.GET.get('new_date', None)
    
      if new_date:
        qset = (
            (
              Q(start_date__lte=new_date) &
              Q(end_date__gte=new_date)
            ) |
            (
              Q(start_date__lte=new_date) &
              Q(end_date__isnull=True)
            )
        )
    
        base_filter = base_filter.filter(qset)
    
      return base_filter
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-05
      • 1970-01-01
      • 2018-06-02
      • 1970-01-01
      • 2021-03-02
      • 1970-01-01
      • 2021-01-16
      • 2017-04-26
      相关资源
      最近更新 更多