【发布时间】:2014-03-14 00:38:54
【问题描述】:
我正在尝试使用教程here 将以下模型序列化为 json。
这是我的模型:
from django.db import models
from django.forms import ModelForm
class Student(models.Model):
student_id = models.IntegerField()
first_name = models.CharField(max_length=32)
middle_name = models.CharField(max_length=24)
last_name = models.CharField(max_length=32)
email = models.CharField(max_length=50)
phone = models.CharField(max_length=16)
cell_phone = models.CharField(max_length=16)
这是我的serializer.py:
from django.forms import widgets
from rest_framework import serializers
from advisorapp.models import Student
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = ('id','student_id','first_name','middle_name','last_name','email','phone','cell_phone')
def restore_object(self, attrs, instance=None):
"""
Create or update a new snippet instance, given a dictionary
of deserialized field values.
Note that if we don't define this method, then deserializing
data will simply return a dictionary of items.
"""
if instance:
instance.student_id = attrs.get('student_id', instance.student_id)
instance.first_name = attrs.get('first_name', instance.first_name)
instance.middle_name = attrs.get('middle_name', instance.middle_name)
instance.last_name = attrs.get('last_name', instance.last_name)
instance.email = attrs.get('email', instance.email)
instance.phone = attrs.get('phone', instance.phone)
instance.cell_phone = attrs.get('cell_phone', instance.cell_phone)
return instance
return Student(**attrs)
但是,当我尝试运行 shell 命令时,我遇到了回溯错误。第一次数据输入成功,但是当我在第二个实例中再次尝试时它给出了错误
(advisingproject)abhishek@abhishek-VirtualBox:~/projects/advisingproject/porta python manage.py shell
Python 2.7.3 (default, Feb 27 2014, 20:00:17)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from advisorapp.models import Student
>>> from advisorapp.serializers import StudentSerializer
>>> from rest_framework.renderers import JSONRenderer
>>> from rest_framework.parsers import JSONParser
>>> Student = Student(student_id=12345)
>>> Student.save()
>>> Student = Student(last_name='yeruva')
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: 'Student' object is not callable
请告诉我哪里出错了
【问题讨论】:
标签: django python-2.7 django-rest-framework