Domanda

Based on the example on this page : https://docs.djangoproject.com/en/dev/topics/db/queries/

class Blog(models.Model):
    name = models.CharField(max_length=100)

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)

I want to find all entries with blog name hello world. There are 2 ways to do it. What's the difference in terms of performance on database ? Is one of them better/preferred?

b = Blog.objets.get(name='hello world')
b.entry_set.all()

OR

Entry.objects.filter(blog__name='hello world')
È stato utile?

Soluzione

The first method is two separate database calls: one to find the Blog, and the second to get the Entry objects. However, each is a simple query with no JOINs.

The second method is only one query, but does a JOIN to find the entries related to the blog with that slug.

Which method you use depends on your use case. For example, if you already have the Blog, then calling entry_set on it directly would be better, because then that's only one simple query. Whereas if you knew the blog ID, rather than the slug, then it would be better to do Entry.objects.filter(blog_id=my_blog_id), as then you're not doing a JOIN at all, so again one simple query.

Altri suggerimenti

I compared them like this

q1 = Blog.objects.get(name='hello world').entry_set.all()
q2 = Entry.objects.filter(blog__name='hello world')

print q1.query
SELECT `entry`.`id`, `entry`.`blog_id` FROM `entry` WHERE `entry`.`blog_id` = 1

print q2.query
SELECT `entry`.`id`, `entry`.`blog_id` FROM `entry` INNER JOIN `blog` ON ( `entry`.`blog_id` = `blog`.`id` ) WHERE `blog`.`name` = 'hello world'

Additionally, as @crazyzubr pointed out, q1 will raise an exception if object is not found or multiple objects are found.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top