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 Tag
s, 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 Tag
s to avoid making an extra query per OA
object:
def home(request):
objetos = OA.objects.prefetch_related('tags')
return render(request, {'objetos': objetos})