djangodjango-modelsdjango-admindjango-admin-filters

customized dropdown value based on foreign key in django admin


My Models

class ServicesMenu(models.Model):
   category = models.CharField(max_length=200)

class Varient(models.Model):
   category = models.ForeignKey(ServicesMenu, on_delete=models.CASCADE)
   varient_Name = models.CharField(max_length=200)

class VarientSubField(models.Model):
   select_Varient = models.ForeignKey(Varient, on_delete=models.CASCADE)
   name = models.CharField(max_length=200)

so the problem is in VariantSubField, its display something like this. enter image description here

here some value are similar i cant change them but i need is to display "category" from ServicesMenu with these VariantSubField dropdown fields.


Solution

  • To customize dropdown text, you should implement the standard _ _ str _ _ method in the relevant model:

    class VarientSubField(models.Model):
       select_Varient = models.ForeignKey(Varient, on_delete=models.CASCADE)
       name = models.CharField(max_length=200)
    
    def __str__(self):
       return self.select_Varient.category + " - " + self.select_Varient.varient_name + " - " + self.name