user3142434
user3142434

Reputation: 305

Render foreign key __str__ method in a template django

class A(models.Model):
   field1 = models.CharField(max_length=10)   
   field2 = models.IntegerField(default=0)

  def __str__(self):
    return self.field1 + str(self.field2)

class B(models.Model):
  a = models.ForeignKey(A)
  ...

Now in a template I want to render the "a" attribute of an instance of model B by using: {{ binstance.a }} but this seems to either render empty string or nothing at all.

How do I render the str methdod of a foreign key within the template?

Upvotes: 0

Views: 1959

Answers (2)

Aurélien
Aurélien

Reputation: 1655

Maybe would I choose a different approach and create a template tag

@register.filter(name='fullname')
def fullname(pk):
    b = B.objects.get(pk=pk)
    field1 = b.a.first_name
    field2 = b.a.last_name
    return "{} {}".format(field1, field2)

Then you can use {{binstance.pk|fullname}}

Upvotes: 0

neverwalkaloner
neverwalkaloner

Reputation: 47364

Actually it's default django behaviour. Check do you pass B instance with template context and use correct variable name in your template.

Upvotes: 5

Related Questions