mysql - 将 sql 转换为 Django ORM

标签 mysql sql django django-orm django-aggregation

如何将此 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/

相关文章:

javascript - 如果用户收到 else 语句,是否可以刷新页面或禁用下一个文本字段?

SQL Server 2012 未在结果中显示 unicode 字符

python - Django REST Framework 和 FileField 绝对 url 在同一字段上

python - 在django模板中相乘

python - django 和 celery+rabbitmq 的消费者连接错误?

php - 使用 php 以 UTF-8 格式导出到 CSV for Excel

mysql - 如何在 PhoneGap 中连接到客户端服务器数据库?

java - 我想使用 Hibernate 查询语言执行存储过程调用,并尝试以 pe 的方式执行此操作

java - 当另一个表添加行时自动创建表行

sql - 将 session 变量传递到 asp :gridview's sqldatasource select command