简体   繁体   English

如何在Django Admin的get_queryset中使用原始SQL?

[英]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来在dbshel​​l中获得所需的结果:

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.

相关问题 如何在Django Admin中使用get_queryset仅检索AdminUser创建的对象? - How use get_queryset in Django Admin for retrieve only objects created by AdminUser? Django在admin中的get_queryset()是否可以防止恶意对象保存? - Does Django's get_queryset() in admin prevent malicious object saving? 带有 LIMIT 的自定义 get_queryset 用于 django 管理面板 - Custom get_queryset with LIMIT for django admin panel Django get_queryset方法的unittest失败 - Django get_queryset method's unittest failing Django的通用视图:如何根据外部类属性过滤get_queryset? - Django's Generic Views: how to filter get_queryset based on foreign class attributes? 更新 Django ListView 中的 get_queryset 后如何更改排序? - How to change ordering after updating get_queryset in Django ListView? 如何在 Django 中的 get_queryset function 中返回多个项目? - How to return multiple items in a get_queryset function in Django? Django如何在get_queryset中按要求传递标头 - Django how to pass header on request in get_queryset 如何在Django中访问get_queryset内部的URL参数? - How to access to URL parameter inside of get_queryset in Django? Django:重写get_queryset()时如何注入数据? - Django: how to inject data when overriding get_queryset()?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM