[英]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.
它包含id,object_id和user_id的列。 When you update a record, instead of updating the row, you create a new record with a matching object_id.
更新记录时,不是更新行,而是使用匹配的object_id创建新记录。
I'm trying to pull all records that match a given user_id with the highest id for each individual object_id. 我正在尝试拉出与给定user_id匹配的所有记录,每个object_id具有最高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. 我尝试使用.raw()方法,但它返回一个RawQuerySet对象,我试图将它提供给需要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? 理想情况下我想摆脱.raw()并使用Django ORM,但如果不可能,我怎样才能将RawQuerySet转换为常规QuerySet?
Please try this: 请试试这个:
from django.db.models import Max
Model.objects.filter(user_id=100).values('object_id').annotate(Max('id'))
If I got you right the table structure is: 如果我找到你,桌面结构是:
----------------------------
| Table |
----------------------------
| id | user_id | object_id |
----------------------------
| 1 | 100 | 10 |
----------------------------
| 2 | 100 | 20 |
----------------------------
| 3 | 200 | 80 |
----------------------------
| 4 | 100 | 80 |
----------------------------
| 5 | 100 | 10 |
----------------------------
And the result of your query should be: 您的查询结果应该是:
----------------------------
| Table |
----------------------------
| id | user_id | object_id |
----------------------------
| 4 | 100 | 80 |
----------------------------
| 2 | 100 | 20 |
----------------------------
| 5 | 100 | 10 |
----------------------------
Then try distinct() , like so: 然后尝试distinct() ,如下所示:
Model.objects.filter(user_id=100).order_by('-object_id', '-id').distinct('object_id')
this should return QuerySet
with your records with user_id
equal 100, then ordered by object_id
first and id
second in descending order, and due to distinct
on object_id
only the first record for each same object_id
will be take, which with the ordering specified will be the one with the highest id
. 这应该返回带有
user_id
等于100的记录的QuerySet
,然后按object_id
排序, id
按降序排序,并且由于object_id
上的distinct
,只有每个相同object_id
的第一条记录将被采用,具有指定的顺序将是一个id
最高的人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.