Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ForeignKey filtering whole object or object_id

I know that object_id is more efficient than object.id but is this rule working for ForeignKey filtering ?

Is

Model.objects.filter(author_id=author_obj.id) 

or

Model.objects.filter(author_id=author_id) 

more efficient than

Model.objects.filter(author=author_obj)
like image 242
Kubas Avatar asked Mar 04 '23 23:03

Kubas


1 Answers

As stated in Queries over related objects section of documentation there's no difference between author_obj.id and author_obj:

For example, if you have a Blog object b with id=5, the following three queries would be identical:

Entry.objects.filter(blog=b) # Query using object instance
Entry.objects.filter(blog=b.id) # Query using id from instance
Entry.objects.filter(blog=5) # Query using id directly

Personally I use entry.blog_id as a rule in my projects as it does not generate extra query.

like image 98
Satevg Avatar answered Apr 27 '23 13:04

Satevg