python - How to write such a mysql statement for GROUP BY in django?
怪我咯
怪我咯 2017-06-07 09:24:57
0
2
782

A newbie in django (also a scumbag in mysql)
I searched on Baidu and tried to write a mysql syntax. I want to use django to write it, but I can’t. I’m here to ask for help.
mysql is

SELECT keywords_id, MAX(id) AS id FROM news_article GROUP BY
keywords_id ORDER BY id DESC LIMIT 0,10

Where 'keywords_id' is the foreign key of the 'news_article' table, in the Article model;

The main purpose is: I want to extract the latest 10 unique data in the 'keywords_id' field in the 'news_article' table, and read the values ​​of other fields (use the mysql syntax to first extract the unique id value, and then use id The values ​​are used as conditions to extract the values ​​​​of other fields and then output to the template page).

I don’t know if the description of the problem is clear, so I’m here to help~

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(2)
PHPzhong

If it is just simple data analysis and processing that does not involve the use of multi-threading in the database, it is recommended to use the pandas module, which has a good groupby method. You can see if it is intuitive and applicable.
django-pandas is available for Django, it is recommended to try it.
The statement of pandas is likely to be written as:

import pandas as pd
...
df = pd.DataFrame(news_article.groupby('keywords_id'))
df.sort_values(by=['id'], ascending = False)[0:10]
世界只因有你
from django.db.models import Max

Article.objects.values('keywords_id').annotate(maxid=Max('id')).order_by['-id'][:10]

The structure is roughly like this, the details may need to be debugged
Reference
https://docs.djangoproject.co...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template