Home  >  Q&A  >  body text

python - How to write such a mysql statement for GROUP BY in django?

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~

怪我咯怪我咯2690 days ago749

reply all(2)I'll reply

  • PHPz

    PHPz2017-06-07 09:26:57

    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]
    

    reply
    0
  • 世界只因有你

    世界只因有你2017-06-07 09:26:57

    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...

    reply
    0
  • Cancelreply