kamilyrb
kamilyrb

Reputation: 2627

Django ORM object.related.id vs object.related_id after used select_related('related')

Let's suppose that we have this models:

class Product(models.Model):
    ....
    price = models.DecimalField(max_digits=12, decimal_places=2)

class Order(models.Model):
    ....
    product= models.ForeignKey(Product)

After used select_related for query like that Order.objects.filter(...).select_related('product'), is there any performance difference between order.product.id and order.product_id?

Upvotes: 0

Views: 167

Answers (1)

GwynBleidD
GwynBleidD

Reputation: 20569

There will be a difference, but not database-related. There is always a performance cost when accessing any object field in Python, so for specified example:

order.product.id

Will need to fetch 2 different attributes from 2 different object, first it needs to fetch product attribute from order, then it needs to fetch id from product.

order.product_id

Will need to fetch only 1 attribute: product_id from order.

This is purely about fetching the correct data from the memory, which is not cost-free in Python, it doesn't involve any IO to database or other resources. This cost, in a lot of the cases is very small and can be omitted, as there will be probably far more similar operations like this in your code.

Upvotes: 2

Related Questions