Search code examples
pythondjangomany-to-many

Django ManyToManyField referenced in loop


My problem looks like this - I have many to many field that I need to reference multiple times in the loop. Each time I have to do it with another id. Every solution I can think of seems pretty heavy and I want to do it nice and clean I'm just out of the ideas (the problem is probably my little experience with Django and Python). Right now I have something like this (it obviously doesn't work):

    projects = Project.objects.order_by('name').values()
    for project in projects:
        currentProject = Project.objects.get(pk=project['id'])
        projects[index] = {
            'genres': currentProject.genres.all().values()
        }
     context = {
     'projects': projects,
     }

I have been looking for the answer for like 2 hours now and couldn't find what I was looking for so I hope someone here can give me some advices. Thanks


Solution

  • Maybe you need to use prefetch_related,

    projects = Project.objects.prefetch_related('genres_set')