如何使用构建自定义SQL查询的最新评论获取blog_post.title?

时间:2012-02-04 20:31:59

标签: python sql database django

sql查询:

select id,title 
from blog_post inner join (select object_pk, max(submit_date) 
                           from django_comments 
                           group by object_pk 
                           order by submit_date DESC) as foo 
where foo.object_pk=blog_post.id;

如何使用django model.objects.get函数获得相同的结果?我如何用django为此编写自定义查询?有什么像

model.objects.getwithsqlquery('''select id,title 
from blog_post inner join (select object_pk, max(submit_date) 
                           from django_comments 
                           group by object_pk 
                           order by submit_date DESC) as foo 
where foo.object_pk=blog_post.id;''')

mysql表是:

mysql> describe blog_post;
+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(11)      | NO   | PRI | NULL    | auto_increment |
| user_id  | int(11)      | NO   | MUL | NULL    |                |
| title    | varchar(100) | NO   |     | NULL    |                |
| content  | longtext     | NO   |     | NULL    |                |
| created  | date         | NO   |     | NULL    |                |
| modified | date         | NO   |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)

mysql> describe django_comments;
+-----------------+--------------+------+-----+---------+----------------+
| Field           | Type         | Null | Key | Default | Extra          |
+-----------------+--------------+------+-----+---------+----------------+
| id              | int(11)      | NO   | PRI | NULL    | auto_increment |
| content_type_id | int(11)      | NO   | MUL | NULL    |                |
| object_pk       | longtext     | NO   |     | NULL    |                |
| site_id         | int(11)      | NO   | MUL | NULL    |                |
| user_id         | int(11)      | YES  | MUL | NULL    |                |
| user_name       | varchar(50)  | NO   |     | NULL    |                |
| user_email      | varchar(75)  | NO   |     | NULL    |                |
| user_url        | varchar(200) | NO   |     | NULL    |                |
| comment         | longtext     | NO   |     | NULL    |                |
| submit_date     | datetime     | NO   |     | NULL    |                |
| ip_address      | char(15)     | YES  |     | NULL    |                |
| is_public       | tinyint(1)   | NO   |     | NULL    |                |
| is_removed      | tinyint(1)   | NO   |     | NULL    |                |
+-----------------+--------------+------+-----+---------+----------------+
13 rows in set (0.00 sec)

1 个答案:

答案 0 :(得分:1)