S
S
Sergey Eremin2015-07-15 00:17:54
Django
Sergey Eremin, 2015-07-15 00:17:54

How to force Django to add GROUP BY to INNER JOIN via ORM?

Actually there is model.py (it doesn't matter which one) and there are a bunch of related tables in it (but everything is fine, without loops and duplication, everything is more or less normalized). And this is how the query looks like:

q=BlogPost.objects.\
        order_by('-dPostDataCreate', 'kBlogAuthorUser__id').\
        select_related()
print q.query

Which generates SQL:
SELECT
    `все-все-все-поля-из-всех-всех-всех-связанных-таблиц-через-запятую`
FROM prj_blogpost
    INNER JOIN prj_ouruser ON ( prj_blogpost.kBlogAuthorUser_id = prj_ouruser.id )
    INNER JOIN auth_user ON ( prj_ouruser.kDjangoUser_id = auth_user.id )
ORDER BY
    prj_blogpost.dPostDataCreate DESC,
    prj_blogpost.kBlogAuthorUser_id ASC

As you may have guessed, in the model, some of the tables are connected via ForeignKey to the Django built-in User class , but this is not important. And it is important that access to the fields in related tables cannot be approached. Those. something like this:
for cnt in q:
        print cnt.username

Generates an error:
Exception Value:	'BlogPost' object has no attribute 'username'

And this is fair, because. in order for everything to work, the ORM needs to spawn a slightly different request:
SELECT
    `все-все-все-поля-из-всех-всех-всех-связанных-таблиц-через-запятую`
FROM prj_blogpost
    INNER JOIN prj_ouruser ON ( prj_blogpost.kBlogAuthorUser_id = prj_ouruser.id )
    INNER JOIN auth_user ON ( prj_ouruser.kDjangoUser_id = auth_user.id )
GROUP BY
    `все-все-все-поля-из-всех-всех-всех-связанных-таблиц-через-запятую` 
ORDER BY
    prj_blogpost.dPostDataCreate DESC,
    prj_blogpost.kBlogAuthorUser_id ASC

The real question is how does the ORM get this GROUP BY
`all-all-all-fields-from-all-all-comma-separated-related-tables`
to be added to the query?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2015-07-15
@Sergei_Erjemin

Sergey Eremin : you are killing me with the name of the variables in the sUserPhone camel case
and rewrite the prefixes
as it should, with underscores and without prefixes
and do not shorten the variable names

posts = BlogPost.objects.\
        order_by('-dPostDataCreate', 'kBlogAuthorUser__id').\
        select_related()

for post in posts:
    print post.kBlogAuthorUser.kDjangoUser.username

and inherit your user from AbstractUser and don't bother with a bunch of models

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question