Search code examples
djangomodeladmin

Django - replace "model object" by the value


I have a model Currency defines below:

class Currency(models.Model):

    """
    Currency Model
    Defines the attribute of Currency
    """

    class Meta:
        verbose_name        = "Currency"
        verbose_name_plural = "Currencies"
        ordering            = ['Currency_Name']

        def __str__(self):
            return self.Currency_Name

    Currency_Date           = models.DateTimeField(auto_now_add=True)
    Currency_Date_Update    = models.DateTimeField(auto_now=True)
    Currency_Name           = models.CharField(max_length=3, unique=True)
    Is_Secondary_Ccy        = models.CharField(max_length=1, choices=Y_N_BOOLEAN)
    Primary_Currency        = models.ForeignKey('self', on_delete=models.DO_NOTHING, null=True)   # to refer to itself
    Primary_Factor          = models.IntegerField(default=1)
    Currency_Name_Reuters   = models.CharField(max_length=3)

The model is linked to itself by the column "Primary_Currency"

In my admin (image below) I can see the linked, but if i open the dropdown, the label is not user friendly "Currency object (0) etc..."

enter image description here

Can I have the value "Currency_Name" of the "Primary_Currency" ?

thanks for your help :)


Solution

  • Use __str__() method of model class,

    class Currency(models.Model):
        ...
    
        # your code
    
        def __str__(self):
            try:
                return self.Primary_Currency.Currency_Name
            except AttributeError:
                return self.Currency_Name