简体   繁体   中英

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

I'm trying to define __str__ function for models A and D for the purpose having human readable text in the admin site. The problem is in model D's __str__ function where __str__ 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM