Get First element by the recent date of each group

2024/10/6 20:32:05

I have following model in django

Business ID
Business Name
Business Revenue
Date

Here is the sample data:

Business ID | Business Name | Business Revenue | Date
1             B1              1000               2012-10-13
2             B2              20000              2013-10-16
1             B1              2000               2013-04-13
2             B2              24000              2014-09-02

I want to fetch all businesses having latest date.

Here is the output I want:

Business ID | Business Name | Business Revenue | Date
1             B1              2000               2013-04-13
2             B2              24000              2014-09-02

I have tried this:

model.objects.filter(date__gte = date.today()).order_by('business_id', '-date')

This is giving me group of businesses having latest business in each group at the top of it. How do I omit the rest of rows? I need some assistance

Answer

If you are using PostgreSQL [docs], you can use order_by() and distinct() methods:

Model.objects.all().order_by('business_id', '-date').distinct('business_id')
https://en.xdnf.cn/q/70325.html

Related Q&A

remote: ImportError: No module named gitlab

I wrote gitlab hook with python. And added to post-receive hooks in gitlab server. When i push to remote origin server from my laptop, i get following error. But it works when i run script manually in …

Using an Access database (.mdb) with Python on Ubuntu [duplicate]

This question already has answers here:Working with an Access database in Python on non-Windows platform (Linux or Mac)(5 answers)Closed 7 years ago.Im trying to use pyodbc to access a .mdb on Ubuntu. …

Pandas Grouper by weekday?

I have a pandas dataframe where the index is the date, from year 2007 to 2017.Id like to calculate the mean of each weekday for each year. I am able to group by year: groups = df.groupby(TimeGrouper(A)…

Can I move the pygame game window around the screen (pygame)

In the game Im making, Im trying to move the window around the screen for a mini game (dont ask) and Ive tried what I saw own threads and only found 1x = 100 y = 0 import os os.environ[SDL_VIDEO_WINDOW…

mocking a function within a class method

I want to mock a function which is called within a class method while testing the class method in a Django project. Consider the following structure: app/utils.py def func():...return resp # outcome i…

After resizing an image with cv2, how to get the new bounding box coordinate

I have an image of size 720 x 1280, and I can resize it to 256 x 256 like thisimport cv2 img = cv2.imread(sample_img.jpg) img_small = cv2.resize(img, (256, 256), interpolation=cv2.INTER_CUBIC)Say I hav…

convert a tsv file to xls/xlsx using python

I want to convert a file in tsv format to xls/xlsx..I tried usingos.rename("sample.tsv","sample.xlsx")But the file getting converted is corrupted. Is there any other method of doing…

How do you edit cells in a sparse matrix using scipy?

Im trying to manipulate some data in a sparse matrix. Once Ive created one, how do I add / alter / update values in it? This seems very basic, but I cant find it in the documentation for the sparse ma…

AttributeError: DataFrame object has no attribute _data

Azure Databricks execution error while parallelizing on pandas dataframe. The code is able to create RDD but breaks at the time of performing .collect() setup: import pandas as pd # initialize list of …

Python: Problem with overloaded constructors

WARNING: I have been learning Python for all of 10 minutes so apologies for any stupid questions!I have written the following code, however I get the following exception: Message FileName Li…