如何在django-rest-framework下拉列表中查看主题名称?现在它只是说Subject object
。
以下是我的模特:
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)
答案 0 :(得分:6)
我发现您为模型定义了__unicode__
。但也许您使用的是Python 3,在这种情况下,对于Django模型,您需要定义__str__
而不是__unicode__
class Subject(models.Model):
...
def __str__(self): # Use this in Python 3
return '%s' % (self.name)
无关,但这是一个更简洁的回报:
def __str__(self):
return self.name