问题
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