Home > Enterprise >  showing ManytoManyField element in a query loop
showing ManytoManyField element in a query loop

Time:10-19

So I want to show elements in a loop from a class I created, however I don't know how to call the ManyToMany element out, can you help me?

class Tag(models.Model):
nametag = models.CharField(max_length=200, null=True)

class OA(models.Model):
tags = models.ManyToManyField(Tag)
...

My function:

def home(request):
objetos = OA.objects.all()
return render(request, {'objetos': objetos})

The problem:

{% for i in objetos %}
...
<tr>{{i.tags.nametag}}</tr>
{% endfor %}

In this case 'nametag' already has a value so it's not empty. I tried a few things but wasn't able to do much, I need help please.

CodePudding user response:

You need to enumerate over the i.tags.all(). Indeed, since this is a ManyToManyField, an OA can have zero, one, or more related Tags, and a Tag can have zero, one or more OA objects.

You thus can implement this with;

<tr>{% for tag in i.tags.all %} {{ tag.nametag }}{% endfor %}</tr>

In the view, you can prefetch the related Tags to avoid making an extra query per OA object:

def home(request):
    objetos = OA.objects.prefetch_related('tags')
    return render(request, {'objetos': objetos})
  • Related