Home > Software engineering >  How to render reverse fields using related name between foreign key models
How to render reverse fields using related name between foreign key models

Time:09-24

I have two models if a foreign key relationship and a related name. I return a queryset of Foo and want to render fields of the related object Bar. However, item.link.value doesn't render anything.

# Models

class Foo(models.Model):
    item


class Bar(models.Model:
    foo = models.Foreignkey(Foo, on_delete=models.CASCADE, related_name='link')
    value = models.Charfield(max_length=20)
# View

def test(request):

    qs = Foo.objects.all()

    context = {
    'qs': qs
    }

return render (request, 'somepage.html', context)
# Template

{% for item in qs %}
<div> {{ item.link.value }} </div>

CodePudding user response:

Try changing your queryset to return instances of Bar, which has the value attribute.

First update your related name on the Bar model to the plural, links:

# Models

class Foo(models.Model):
    item


class Bar(models.Model:
    foo = models.Foreignkey(Foo, on_delete=models.CASCADE, related_name='links')
    value = models.Charfield(max_length=20)

If you now ask for Foo.links.all(), Django will return a queryset of Bar instances.

# View
def test(request):

    qs = Foo.links.all()

    context = {
    'qs': qs
    }

return render (request, 'somepage.html', context)
  • Related