Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select from a subquery using the Django ORM?

I have a table that is meant to be insert only. It has columns for id, object_id, and user_id. When you update a record, instead of updating the row, you create a new record with a matching object_id.

I'm trying to pull all records that match a given user_id with the highest id for each individual object_id.

I can do what I'm attempting to describe with a subquery like so:

SELECT * FROM (SELECT * FROM table WHERE user_id = 100 ORDER BY object_id, id DESC) adr_table GROUP BY object_id

I've tried using the raw() method, but it returns a RawQuerySet object and I'm trying to feed it to a form that needs a QuerySet.

I'd ideally like to get rid of the raw() and just use the Django ORM, but if that isn't possible, how can I convert the RawQuerySet to a regular QuerySet?

like image 387
Alex K Avatar asked Mar 09 '26 09:03

Alex K


1 Answers

Please try this:

from django.db.models import Max

Model.objects.filter(user_id=100).values('object_id').annotate(Max('id'))
like image 106
Shang Wang Avatar answered Mar 11 '26 23:03

Shang Wang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!