views:

116

answers:

2

Hi guys, how can I execute such query in django:

SELECT * FROM keywords_keyword WHERE id not in (SELECT keyword_id FROM sites_pagekeyword)

In the latest SVN release we can use:

keywords = Keyword.objects.raw('SELECT * FROM keywords_keyword WHERE id not in (SELECT keyword_id FROM sites_pagekeyword)')

But RawQuerySet doesn't support filter(), count(), indexing and other things. Is there another way?

+8  A: 

Keyword.objects.exclude(id__in=PageKeyword.objects.all()

Keyword.objects.exclude(id__in=PageKeyword.objects.values('keyword_id'))

For future reference, exclude is documented here.


Edit: Yes, you are right; I corrected my answer. See above.


Edit: Even more readable:

Keyword.objects.exclude(pagekeyword__in=PageKeyword.objects.all())
celopes
Yep thanks, I forgot about exclude()
t0ster
+1  A: 

I've tested your code and it works not as expected, here is the right solution for my task:

Keyword.objects.exclude(id__in=PageKeyword.objects.values('keyword_id'))
t0ster
Yes, you are right. I corrected my answer. Sorry about that.
celopes
I actually think the latest edit to my answer makes it even more readable...
celopes