Kritz
Kritz

Reputation: 7311

Django efficient lookups: Related manager vs whole queryset

Let's say I have the following Django models:

class X(models.Model):
    some_field = models.FloatField()


class Y(models.Model):
    x = models.ForeignKey(X)
    another_field = models.DateField()

Let's say I'm looking for a particular instance of y, with a certain date (lookup_date), belonging to a certain x. Which option would be a more efficient lookup, if any?:

1. Y.objects.get(x=x, another_field=lookup_date)

or using the related manager:

2. x.y_set.get(another_field=lookup_date)

Upvotes: 2

Views: 370

Answers (1)

Sayse
Sayse

Reputation: 43300

You'll probably find that they produce the same query, you can check this by adding .query to the end of the query which will show the resulting sql.

Y.objects.get(x=x, another_field=lookup_date).query
x.y_set.get(another_field=lookup_date).query

But either way this is a micro optimization and you may find it interesting to read Eric Lippert's performance rant.

Is one of them considered more pythonic?

Not really, I tend to use the second since it can make it slightly easier to conform to pep8's line length standard

Upvotes: 3

Related Questions