Skip to content
thesarfo

Note

F Objects for Referencing Fields

Comparing one model field to another within a filter using F objects, including referencing fields across relationships.

views 0

Let’s say during filtering, we want to return all the products that have their inventory = unit_price. This doesnt really make sense in terms of logic but anyways.

The inventory is a string and the unit_price is an integer. How do we compare them, that’s where the F object comes in. See below

from django.db.models import F
queryset = Product.objects.filter(inventory=F("unit_price"))

The “unit_price” can be replaced with the name of any field you want to reference.

With F objects you can also reference collections in a different table. See below

from django.db.models import F
queryset = Product.objects.filter(inventory=F("collection__id"))