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?
Please try this:
from django.db.models import Max
Model.objects.filter(user_id=100).values('object_id').annotate(Max('id'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With