JTheboss JTheboss - 3 months ago 27
Python Question

Django __str__ function on many to one field is not returning the correct output

I'm trying to define

function for models A and D for the purpose having human readable text in the admin site. The problem is in model D's
function where
will return a many_to_one related field, it does not return the format as intended instead it just showa the default 'D object'.

class A(models.Model):
b = models.CharField(max_length = 32)
c = models.CharField(max_length = 32)

def __str__(self):
return '%s %s' % (self.b, self.c)

class D(models.Model):
e = models.ForeignKey(A)

def __str_(self):
return '%s %s' % (self.e.b, self.e.c)


You've got a typo in your method name. You wrote __str_() when it should be __str__(). So when you're calling str() on your model, it's calling the inherited __str__() method from the parent class.