These are chat archives for django/django

16th
Jan 2016
ikhahmedov
@ikhahmedov
Jan 16 2016 13:03

@friendOfOurs : first of all I guess you are doing something wrong, if you want to get QuerySet of Users from Level, you should do it in different order

Users.objects.filter(userprofile__in=Level.objects.filter(id=3))

You will get all users whose level = 3, and probably Django ORM will save some queries for you by doing

SELECT users.* FROM  users u
INNER JOIN userprofile up ON up.user_id = u.id 
WHERE up.level_id IN (SELECT level.id FROM level WHERE id = 3)
friendOfOurs
@friendOfOurs
Jan 16 2016 13:06
@ikhahmedov omg, that makes so much sense! Thanks! I was about to get rid of UserProfile model ^^ Thanks again!
ikhahmedov
@ikhahmedov
Jan 16 2016 13:07
@friendOfOurs : welcome, by the way seems I made mistake
Users.objects.filter(userprofile__level__in=Level.objects.filter(id=3))

if filtering from User profile doesn't work, try to use UserProfile model then at the end add select_related

UserProfile.objects.filter(level__in=Level.objects.filter(id=3)).select_related('user')

select_related decreases queries to db

friendOfOurs
@friendOfOurs
Jan 16 2016 13:13
yep, looks good. but just out of curiosity: since I am going to be needing user's level a lot, maybe it wouln't be a bad idea to have the field directly in my auth user model?
ikhahmedov
@ikhahmedov
Jan 16 2016 13:15
if you are using Django > 1.7 they have added AUTH_USER_MODEL setting so that you can inherit from User model and create your own Model, if you need level a lot, then in select_related() add 'level' --> select_related('user','level') than db will get only one query, otherwise you for each .level access ORM will send query to db see (N+1) problem in database theory
friendOfOurs
@friendOfOurs
Jan 16 2016 13:22
(y) thanks
sandivorace
@sandivorace
Jan 16 2016 19:04
thank you @bittner ...
you're very cool