R
R
Rrooom2014-10-02 18:19:22
Django
Rrooom, 2014-10-02 18:19:22

Is it possible to "join" django queryset with custom sql query?

There is a rather complex aggregating (? like so) query.

SELECT mymodel.id as id,
SUM(...),
SUM(...)
COUNT(...)
FROM anothermodel
JOIN ... JOIN ...
WHERE mymodel.id IN (1,2,3,4)
GROUP BY mymodel.id,  anothermodel.country

It can be easily called - MyModel.objects.raw(query). Separately, it works fine - and the aggregated data is available and the model fields are automatically joined by id.
Is it possible vice versa? There is a queryset MyModel.objects.filter(...).exclude(...). How to attach raw request data to it? Ordinary extras are not suitable, because the data is retrieved from another table (which is connected through four foreign keys).

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Podgursky, 2014-10-09
@kmmbvnr

It is possible through extra / where, just the request will not be through join, but through a subquery
select ... where id not in (select ...)

I
ivique, 2015-02-01
@ivique

Make a database view from the request and add it as an unmanaged model.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question