如何将此 SQL 转换为 Django ORM
SELECT
`table1`.*,
`tabl2`.*
FROM `table1`
INNER JOIN `table2` ON (`table1`.`table2_id` = `table2`.`id`)
INNER JOIN
(SELECT
table2_id,
MAX(date) AS max_date
FROM table1
WHERE date <= CURRENT_DATE
GROUP BY table2_id) grouped
ON table1.table2_id = grouped.table2_id
AND table1.date = grouped.max_date
WHERE `table1`.`table2_id` IN (73, 74)
ORDER BY `table1`.`date` ASC
我尝试使用注释,但不成功
最佳答案
简单地说,您需要为表定义模型,即“table1”和“table2” - 使用 ORM 的要点是将表定义为模型(一次性)并轻松进行查询。
如果您定义了架构,请将其转换为 Django 模型(所有字段)。并且,如果您已经设置了数据库,请使用 inspectdb
命令从数据库自动生成模型。
您可以为特定数据库表生成模型 - inspectdb
.
<小时/>inspectdb
django-admin inspectdb [table [table ...]]
Introspects the database tables in the database pointed-to by the NAME setting and outputs a Django model module (a models.py file) to standard output. You may choose what tables to inspect by passing their names as arguments.
Use this if you have a legacy database with which you’d like to use Django. The script will inspect the database and create a model for each table within it.
As you might expect, the created models will have an attribute for every field in the table. Note that inspectdb has a few special cases in its field-name output:
If inspectdb cannot map a column’s type to a model field type, it’ll use TextField and will insert the Python comment 'This field type is a guess.' next to the field in the generated model.
If the database column name is a Python reserved word (such as 'pass', 'class' or 'for'), inspectdb will append '_field' to the attribute name. For example, if a table has a column 'for', the generated model will have a field 'for_field', with the db_column attribute set to 'for'. inspectdb will insert the Python comment 'Field renamed because it was a Python reserved word.' next to the field.
但是您必须手动验证自动生成的模型:
This feature is meant as a shortcut, not as definitive model generation. After you run it, you’ll want to look over the generated models yourself to make customizations. In particular, you’ll need to rearrange models’ order, so that models that refer to other models are ordered properly.
关于mysql - 将 sql 转换为 Django ORM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43110525/