Tastypie & raw sql

独自空忆成欢 提交于 2019-12-11 03:09:02

问题


How do I get Tastypie to fetch a raw sql queryset? queryset = Foo.objects.raw(sql) does not seem to be working. Is it not possible?


回答1:


queryset = super(class_name, self).get_query_set()
return queryset.whatever()



回答2:


This seems to work:

class BarResource(ModelResource):

    class Meta:
        queryset = Bar.objects.all()

    def dehydrate(self, bundle):
        qs = Bar.objects.raw('SELECT * FROM foo_bar')
        return [row for row in qs]



回答3:


You can try to override the dehydrate function to include raw sql syntax and or make a Per-Request Alterations To The Queryset http://django-tastypie.readthedocs.org/en/latest/cookbook.html

I personally would much rather create a custom view function in view.py that matches whatever your api REST syntax is - for example /api/v1/rawsql something like that to keep your patterns the same - you'd just be managing it differently.




回答4:


This works to me :D

class UsersResource(ModelResource):
    class Meta:
        resource_name   = "users"
        queryset        = User.objects.all()
        allowed_methods = ['get']

   def obj_get_list(self, bundle, **kwargs):
        query = """
        SELECT 
            id, name
        FROM 
            users 
        ORDER BY name"""         
        qs = User.objects.raw(query)
        return [row for row in qs]


来源:https://stackoverflow.com/questions/14793785/tastypie-raw-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!