user1283776 user1283776 - 4 months ago 23
Python Question

See description in django-rest-framework dropdown?

How can I see the Subject name in the django-rest-framework dropdown? Now it just says

Subject object
.

enter image description here

Here are my serializers:

class Subject(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
owner = models.ForeignKey('auth.User', related_name='subjects')
code = models.CharField(max_length=50)
name = models.CharField(max_length=50)
description = models.CharField(max_length=50)

class Meta:
ordering = ('created',)

def __unicode__(self):
return '%s' % (self.name)

class Grade(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
owner = models.ForeignKey('auth.User', related_name='grades')

code = models.CharField(max_length=3)
requirements = models.CharField(max_length=200)
ranking = models.IntegerField()

subject = models.ForeignKey(Subject, related_name='grades', on_delete=models.CASCADE)

class Meta:
unique_together = ('subject', 'ranking')
ordering = ('ranking',)

def __unicode__(self):
return '%d: %s' % (self.ranking, self.code)

Answer

I see you have defined __unicode__ for your model. But perhaps you are using Python 3, in which case for Django models you need to define __str__ not __unicode__

class Subject(models.Model):
    ...

    def __str__(self):                # Use this in Python 3
        return '%s' % (self.name)

Unrelated, but this is a more succinct return:

    def __str__(self):
        return self.name
Comments