Django Querysets Advanced queries with F objects


An F() object represents the value of a model field or annotated column. It makes it possible to refer to model field values and perform database operations using them without actually having to pull them out of the database into Python memory. - F() expressions

It is appropriate to use F() objects whenever you need to reference another field's value in your query. By itself, F() objects do not mean anything, and they cannot and should not be called outside of a queryset. They are used to reference a field's value on the same queryset.

For example, given a model ...

    some_field = models.IntegerField()

... a user can query objects where the some_field value is twice its id by referencing the id field's value while filtering using F() like this:

SomeModel.objects.filter(some_field=F('id') * 2)

F('id') simply references the id value for that same instance. Django uses it to create corresponding SQL statement. In this case something closely resembling this:

SELECT * FROM some_app_some_model 
WHERE some_field = ((id * 2))

Without F() expressions this would be accomplished with either raw SQL or filtering in Python (which reduces the performance especially when there are lots of objects).


From F() class definition:

An object capable of resolving references to existing query objects. - F source

Note: This example posted came from the answer listed above with consent from TinyInstance.