Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define the __str__ method for a foreignkey field in Django?

How do I define the str method for a foreignkey field in Django? The code below does not work,

class A(models.Model):
    name = models.ForeignKey('B')

def __str__(self):
    return self.name
like image 367
Devone Avatar asked Aug 04 '16 19:08

Devone


1 Answers

If your model B has a name field, you could:

def __str__(self):
    return self.name.name

Or you could try define the __str__ method in B model.

like image 141
Gocht Avatar answered Sep 22 '22 19:09

Gocht