1👍
✅
Saving the City values in both Person and Address models would lead to Data Duplication. While designing models or tables, we must avoid data duplication.
We can display the values of both Person and Address models in AddressAdmin list_display itself.
Define a method nick_name
in AddressAdmin class with args as self and obj
. Through obj args we can get the values of foreign key fields and paste the method name in list_display.
#models.py
class Person(models.Model):
name = models.CharField(max_length=200)
nick_name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Address(models.Model):
name = models.ForeignKey(Person)
city = models.CharField(max_length=200)
def __str__(self):
return self.name
#admin.py
class AddressAdmin(admin.ModelAdmin):
list_display = ('nick_name', 'city')
def nick_name(self, obj):
return obj.name.nick_name
Source:stackexchange.com