返回特定的对象属性序列化器Django Rest框架

时间:2014-05-16 18:12:46

标签: python django django-rest-framework

我有以下代码,它可以工作,但它返回以下内容。如何更改它以显示subject.s字段而不是返回完整的对象(Subjects对象)?有任何想法吗?感谢。

{
    "name": "Andres", 
    "nick": "andresito", 
    "avatar_s": "", 
    "rate": 50, 
    "id": 3, 
    "subjects": [
        "subjects object", 
        "subjects object"
    ]
}

它应该返回

{
    "name": "Andres", 
    "nick": "andresito", 
    "avatar_s": "", 
    "rate": 50, 
    "id": 3, 
    "subjects": [
        "Web Development", 
        "User Experience"
    ]
}

我的models.py是:

class subjects(models.Model):

#id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase.
id_user = models.IntegerField(db_column='ID_user') # Field name made lowercase.
s = models.CharField(max_length=90)
grade = models.IntegerField()
ss = models.CharField(max_length=100)
id_school = models.IntegerField(db_column='ID_school') # Field name made lowercase.
subject_area = models.CharField(max_length=20)
subject_number = models.CharField(max_length=30)
subject_section = models.CharField(max_length=10)
current = models.IntegerField()

class Meta:
    db_table = 'subjects'

class users(models.Model):
#id = models.IntegerField(db_column='ID')  # Field name made lowercase.
nick = models.CharField(unique=True, max_length=60)
name = models.CharField(max_length=80)
rate = models.CharField(max_length=2)
avatar_s = models.CharField(max_length=160)



def user_subjects(self):

    subject = subjects.objects.filter(id_user=self.id)
    return subject

class Meta:

    db_table = 'users'

我的Serializers.py是

类UserKarmaSerializer(serializers.HyperlinkedModelSerializer):

subjects = serializers.Field(source='user_subjects')

class Meta:
    model = users
    fields = ('name', 'nick', 'avatar_s', 'rate', 'id', 'subjects')

1 个答案:

答案 0 :(得分:0)

答案就是在字段中添加一个unicode,然后返回到模型主题

def __unicode__(self):
    return self.s