How do I define the __str__ method for a foreignkey field in Django?
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.
Table 'A' has a Foreign Key of Table 'B', You can Define like this:
class B(models.Model): something=models.CharField(max_length=50)class A(models.Model): name = models.ForeignKey('B') def __str__(self): return self.name.something
@Gocht has the correct answer, the code at the moment is basically calling the str method of your Model B, which is presumably unset.
You can reference foreign key fields in the STR box, but unless you also set list_display on the ModelAdmin for Model A I'd not reccomend it if you need a responsive admin module.
You will end up with literally thousands of queries for each page load. Any bulk deletion task will become a vision of eggtimers..