[英]How to use raw SQL in Django Admin's get_queryset?
I am trying to use Model.objects.raw()
in Django Admin but end up with a generic database error: "Something's wrong with your database installation. Make sure the appropriate database tables have been created, and make sure the database is readable by the appropriate user." 我正在尝试在Django Admin中使用Model.objects.raw()
,但最终出现一个通用数据库错误:“您的数据库安装有问题。请确保已创建适当的数据库表,并确保该数据库可被适当的用户。”
admin.py admin.py
class ChapterAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields':['title','shorthand','description',]})
]
list_display = ('shorthand','title')
def get_queryset(self, request):
queryset = super(ChapterAdmin, self).get_queryset(request)
sql = "SELECT * FROM myapp_chapter"
queryset = Chapter.objects.raw(sql)
return queryset
models.py models.py
class Chapter(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(max_length=800, blank=True, null=True)
shorthand = models.SlugField(max_length=3, unique=True, null=True)
def __str__(self):
return self.shorthand
Everything functions if queryset
is set to Chapter.objects.all()
instead of Chapter.objects.raw(sql)
, so I initially assumed that my raw SQL was incorrect. 如果将queryset
设置为Chapter.objects.all()
而不是Chapter.objects.raw(sql)
,那么所有功能都会起作用,因此我最初认为我的原始SQL不正确。 I also read that errors can occur if Models.objects.raw()
fails to return rows. 我还读到,如果Models.objects.raw()
无法返回行,则会发生错误。 However, running SELECT * FROM myapp_chapter
in dbshell
returns everything normally. 但是,在dbshell
运行SELECT * FROM myapp_chapter
正常返回所有内容。 How do I get a queryset using raw SQL in Django Admin? 如何在Django Admin中使用原始SQL获取查询集?
For context on why I am choosing to use raw SQL, the shorthand
contains a mixture of numeric and alphanumeric values that I need sorted naturally: 关于我为什么选择使用原始SQL的上下文, shorthand
包含我需要自然排序的数字和字母数字值的混合:
1
10
11
4
5
7A
7B
I get the results I want in dbshell using SELECT * FROM myapp_chapter ORDER BY shorthand*1, shorthand
: 我使用SELECT * FROM myapp_chapter ORDER BY shorthand*1, shorthand
来在dbshell中获得所需的结果:
1
4
5
7A
7B
10
11
However, I couldn't find a way to achieve this result without using raw SQL. 但是,如果不使用原始SQL,我将找不到实现此结果的方法。 Is there a better way to achieve this without using raw SQL? 有没有更好的方法,而无需使用原始SQL?
Getting the SQL from a query is not all that hard: Getting the SQL from a Django QuerySet It's only rarely the right solution though, besides debugging I wouldn't recommend it. 从查询中获取SQL并不那么困难: 从Django QuerySet中获取SQL尽管很少调试,但除调试之外,我不建议这样做。
The better solution would be to either use extra()
through the Django ORM or by creating an extra column (which will be loads faster since the latter can use an index): Django QuerySet ordering by expression 更好的解决方案是通过Django ORM使用extra()
或创建一个额外的列(由于后者可以使用索引,因此加载速度更快): Django QuerySet按表达式排序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.