我在测试GET请求时跟踪了一些过时的tutorialand,该请求期望获取所有用户列表我收到错误:
'QuerySet' object has no attribute 'append'
下面是UserProfile模型。
class UserProfile(models.Model):
user = models.OneToOneField(User)
nickname = models.CharField(max_length = 128)
comment = models.TextField()
country = models.CharField(max_length = 128, blank = True)
url = models.CharField(max_length = 128, blank = True)
ignores = models.ManyToManyField(User, related_name = 'ignore_set', blank = True, null = True)
def serialize(self):
data = {
'user':self.user_id,
'username':self.user.username,
'nickname':self.nickname,
'comment':self.comment,
'country':self.country,
'url':self.url,
'ignores':[],
}
return data
下面是view.py(请参阅 api / user / list )
def user_view(request, method):
# api/user/create: api that creating new account.
if method == 'create' and request.method == 'POST':
...
#api/user/update: api that update user's oldpassword with new one
elif method == 'update' and request.method == 'POST':
...
elif method == 'list':
users = UserProfile.objects.all()
return toJSON(serial(users))
else:
return toJSON({'status':'bad request'},400)
我想下面的序列化函数是问题的根源..但不知道如何解决它..
def serial(objs):
serialized = []
for obj in objs:
objs.append(obj.serialize())
return serialized
def toJSON(objs, status=200):
j = json.dumps(objs, ensure_ascii=False)
return HttpResponse(j, status=status, content_type='application/json; charset=utf-8')
答案 0 :(得分:0)
您的序列函数附加了错误的内容(objs
而不是serialized
)
def serial(objs):
serialized = []
for obj in objs:
objs.append(obj.serialize())
return serialized
应该是
def serial(objs):
serialized = []
for obj in objs:
serialized.append(obj.serialize())
return serialized