Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin foreign key drop down field list only "test object"

I have these two classes:

class Test(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(User)
    groups = models.ManyToManyField(Group)

class TestSubjectSet(models.Model):
    id =  models.AutoField(primary_key=True)
    test = models.ForeignKey(Test)
    subject = models.ManyToManyField(Subject)

The TestSubjectSet form test list shows only string "test object".

like image 446
kelvinfix Avatar asked May 02 '11 06:05

kelvinfix


People also ask

Can a Django model have 2 foreign keys?

First of all, anything is possible. Models can have multiple foreign keys.

How does Django foreign key work?

Introduction to Django Foreign Key. A foreign key is a process through which the fields of one table can be used in another table flexibly. So, two different tables can be easily linked by means of the foreign key. This linking of the two tables can be easily achieved by means of foreign key processes.


2 Answers

You have to add __unicode__(self) or __str__(self) methods in your models class.

http://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#django.db.models.Model.unicode

like image 58
Sivasubramaniam Arunachalam Avatar answered Oct 26 '22 22:10

Sivasubramaniam Arunachalam


Had the same problem. Adding

def __str__(self):
    return self.user

solved the problem.

like image 28
Alex Jolig Avatar answered Oct 26 '22 23:10

Alex Jolig