Prefetch_related () joins all first elements

I am pretty sure that something is wrong here, but I cannot understand.

In my application, elements can be saved in Workspaces, as shown below:

# models.py    
class Item(models.Model):
    name = models.CharField()

class Workspace(models.Models):
    name = models.CharField()
    items = models.ManyToManyField(
        Item,
        related_name="workspaces",
        null=True,
        blank=True,
        default=None)

Then in my ListView, I want to display items and their associated workspaces:

# views.py
class ListItems(ListView):
    model = Items
    template_name = "list_items.html"
    def get_queryset(self):
        return self.model.objects.all().prefetch_related('workspaces')

Error in my template:

# list_items.html
{% for object in object_list %}

    {{ object.name }}
    Workspaces : 
    {% for workspace in object.workspaces.all %}
        {{ workspace.name }}
    {% empty %}
        No workspaces
    {% endfor %}
{% endfor %}

Say I have 10 different items and one folder called "Foo". Instead of displaying my template as follows:

Item1
workspaces: Foo

Item2
workspaces: Foo

Item3
workspaces: Foo

#etc...

I get the following output:

Item1
workspaces: Foo Foo Foo Foo Foo Foo Foo Foo Foo Foo # 1 Foo per item in list

Item2
workspaces: No workspaces

Item3
workspaces: No workspaces

#etc...

It seems that prefetch_related () associates all workspaces with the first item in the list. If I remove the prefetch_related () get_queryset () part, I get the correct output, but it requires more requests.

What am I doing wrong here?

, , , . , get_queryset() prefetch_related(). , .

!

+4
1

, : django-polymorphic . som e , prefetch_related , .

django-polymorphic tracker: https://github.com/chrisglass/django_polymorphic/issues/68

, , .

+1

All Articles