Django - preventing join when querying foreign key ids?

Let's say I have a simple model for writing in Django:

class Entry(models.Model): author = models.ForeignKey(Author) topic = models.ForeignKey(Topic) entry = models.CharField(max_length=50, default='') 

Now say that I want to request an author or topic, but I completely exclude a specific topic.

 entry_list = Entry.objects.filter(Q(author=12)|Q(topic=123)).exclude(topic=666) 

Simple enough, but I found that this raw SQL contains a join in the subject table, although it does not need to be used:

 SELECT `blog_entry`.`id` FROM `blog_entry` LEFT OUTER JOIN `blog_topic` ON (`blog_entry`.`topic_id` = `blog_topic`.`id`) WHERE ((`blog_entry`.`author_id` = 12 OR `blog_entry`.`topic_id` = 123 ) AND NOT ((`blog_topic`.`id` = 666 AND NOT (`blog_topic`.`id` IS NULL) AND `blog_topic`.`id` IS NOT NULL )) ) 

Why? How can I get Django to only query column identifiers and not join tables? I tried the following, but it gave a FieldError:

 entry_list = Entry.objects.filter(Q(author_id=12)|Q(topic_id=123)).exclude(topic_id=666) 
+4
source share
1 answer

I wonder if this is a mistake.

having tried a similar example, I don't get any connection when placing exclude before filter (but I will get it using your order)

+2
source

Source: https://habr.com/ru/post/1389230/


All Articles