Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango-taggit prefetch_related
    primarykey
    data
    text
    <p>I'm building a basic time logging app right now and I have a todo model that uses django-taggit. My Todo model looks like this:</p> <pre><code>class Todo(models.Model): project = models.ForeignKey(Project) description = models.CharField(max_length=300) is_done = models.BooleanField(default=False) billable = models.BooleanField(default=True) date_completed = models.DateTimeField(blank=True, null=True) completed_by = models.ForeignKey(User, blank=True, null=True) tags = TaggableManager() def __unicode__(self): return self.description </code></pre> <p>I'm trying to get a list of unique tags for all the Todos in a project and I have managed to get this to work using a set comprehension, however for every Todo in the project I have to query the database to get the tags. My set comprehension is:</p> <pre><code>unique_tags = { tag.name.lower() for todo in project.todo_set.all() for tag in todo.tags.all() } </code></pre> <p>This works just fine, however for every todo in the project it runs a separate query to grab all the tags. I was wondering if there is any way I can do something similar to prefetch_related in order to avoid these duplicate queries:</p> <pre><code>unique_tags = { tag.name.lower() for todo in project.todo_set.all().prefetch_related('tags') for tag in todo.tags.all() } </code></pre> <p>Running the previous code gives me the error: </p> <pre><code>'tags' does not resolve to a item that supports prefetching - this is an invalid parameter to prefetch_related(). </code></pre> <p>I did see that someone asked a very similar question here: <a href="https://stackoverflow.com/questions/12204511/optimize-django-query-to-pull-foreign-key-and-django-taggit-relationship">Optimize django query to pull foreign key and django-taggit relationship</a> however it doesn't look like it ever got a definite answer. I was hoping someone could help me out. Thanks!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload