Search code examples
pythondjangodjango-modelsdjango-admindjango-filters

How to Display the attribute value and not the ParentEvent Object in the Foreign key dropdown?


I have the followiung models:

class ParentEvents(models.Model):
    name=models.CharField(max_length=70)

class Event(models.Model):
    name = models.CharField(max_length=70)
    side_list = models.TextField()
    parent_event=models.ForeignKey('ParentEvents')

now when i registered the Event class in admin.py it displays "ParentEventObjects" in the dropdown list of foreign key. How can i change it so that instead of ParentEventObjects it displays the name field of the parent event. thanks in advance :)


Solution

  • You need to add the __unicode__ attribute for the name to show up.

    class ParentEvents(models.Model):
        name=models.CharField(max_length=70)
    
        def __unicode__(self):
            return u"%s" % self.name
    

    The same for Event model as you would run into similar issues for the same.

    Read more on __unicode__ here