1

我对 Python 很陌生,我已经看到了

Entries.objects.raw("SELECT * FROM register_entries")

Entries.objects.filter()

做同样的查询。

在哪种情况下使用其中一种更好?

4

2 回答 2

5

It depends on the database backend that you are using. The first assume that you have a SQL-based database engine. That is not always true. At the opposite, the second one will work in any case (if the backend is designed for). There was for instance few years ago a LDAP backend which was designed so, but LDAP queries do not use SQL language at all.

In all cases, I advice you to use the second one. It is the better way to go if you want to make reusable and long-term code.

There are also other ideas to prefer the second one to the first one

  • avoiding possible SQL injections ;
  • no need to know about database design (table's name, fields' name) ;
  • generic code is better than specific one ;
  • and moreover, it is shorter...

But you sometimes will have to use the first one when you do specific operations (calling specific backend's functions), but avoid them as much as possible.

In a nutshell, use the second one!!!

于 2013-06-29T13:53:37.903 回答
1

来自 django文档

当模型查询 API 不够远时,您可以退回到编写原始 SQL

对于所有方面,django queryset api 为您提供了许多自定义查询的选项。但在某些情况下,您需要在 django api 不足的情况下使用非常具体的查询。但在使用原始 SQL 之前,最好阅读所有 Queryset Api 文档并了解有关 django queryset api 的所有信息。

于 2013-06-29T13:59:24.983 回答