4

Defining a custom Django user combined with django-taggit I have ran into an ORM issue, I also have this issue in the django admin filters.

NOTE: I am using this snippet: https://djangosnippets.org/snippets/1034/

# User

id   | first_name
---------------------------------
1    | John
2    | Jane

# MyUser

usr_ptr_id | subscription
---------------------------------
1          | 'A'
2          | 'B'

Now when I use the django ORM to filter on certain tags for MyUser, e.g.

MyUser.objects.filter(tags__in=tags)

I get the following error:

(1054, "Unknown column 'myapp_user.id' in 'on clause'")

The printed raw query:

SELECT `myproject_user`.`id`, `myproject_user`.`first_name`, `myapp_user`.`user_ptr_id`, `myapp_user`.`subscription` 
FROM `myapp_user` INNER JOIN `myproject_user` 
ON ( `myapp_user`.`user_ptr_id` = `myproject_user`.`id` ) 
INNER JOIN `taggit_taggedtag` 
ON ( `myapp_user`.`id` = `taggit_taggedtag`.`object_id` 
AND (`taggit_taggedtag`.`content_type_id` = 31)) 
WHERE (`taggit_taggedtag`.`tag_id`) 
IN (SELECT `taggit_tag`.`id` FROM `taggit_tag` WHERE `taggit_tag`.`id` IN (1, 3)))

Changing 'id' to 'user_ptr_id' in the second ON part makes the query work is there any way to force this with the Django ORM ?

user2298943
  • 632
  • 5
  • 20

1 Answers1

1

The issue is that you can't look for an ID in a list of Tags; you need to look for the ID in a list of IDs. To fix this, construct a values_list of all of the IDs you want to filter by, and then pass that list off to your original query instead.

id_list = Tag.objects.all().values_list("id")
MyUser.objects.filter(tags__in=id_list)

If you have a many_to_many rleationship between MyUser and Tag, you can also just use the manytomany manager in place of the whole thing:

MyUser.tags.all()
Robert Townley
  • 3,414
  • 3
  • 28
  • 54