如何使用Django ORM查詢重寫原始SQL查詢(MySQL) ?

[英]How to rewrite Raw SQL Query (MySQL) with Django ORM query?


How to rewrite next Raw SQL Query (MySQL) with Django ORM query?

如何用Django ORM查詢重寫下一個原始SQL查詢(MySQL) ?

mysql> select author_id, 
              count(*) c 
        from library_books 
       group by author_id 
      having c>2 
       limit 3;

+---------------+----+

|     author_id | c  |

+---------------+----+

|             0 | 39 |

|          1552 | 17 |

|          1784 |  8 |

+---------------+-----

1 个解决方案

#1


2  

First, annotate an author queryset with the number of books.

首先,用書籍的數量來注釋一個作者。

from django.db.models import Count
authors = Author.objects.annotate(num_books=Count('librarybook')

You haven't shown your Django models, so I've had to guess that 'librarybook' is the correct name for the reverse relationship.

你沒有展示你的Django模型,所以我不得不猜測“librarybook”是反向關系的正確名稱。

Then filter on the num_books to find authors with more than two books.

然后在num_books上進行篩選,找到有兩本書以上的作者。

authors = Author.objects.annotate(num_books=Count('librarybook').filter(num_books__gt=2)

Finally, slice the queryset to limit it to 3 results.

最后,將queryset分割為3個結果。

authors = Author.objects.annotate(num_books=Count('librarybook').filter(num_books__gt=2)[:3]

You can then loop through the resulting authors and access the number of books.

然后,您可以遍歷結果的作者並訪問圖書的數量。

for author in authors:
    print author.name, author.num_books

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/07/22/72110dc72ba6e99f15d24a47fbf8f3b0.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com