我很想在django rest框架中开发API。我想为app mobile创建API。
该服务具有以下功能:
型号:
class Users(models.Model):
sync_id = models.BigIntegerField(primary_key=True)
points = models.IntegerField()
phone = models.CharField(max_length=50, blank=True, null=True)
email = models.CharField(max_length=50, blank=True, null=True)
def __unicode__(self):
return self.sync_id
def save(self, *args, **kwargs):
sequence_name = 'SEQ_ID'
# Query the database for the next sequence value.
from django.db import connection
cursor = connection.cursor()
cursor.execute("SELECT %s.nextval FROM DUAL;" % (sequence_name))
row = cursor.fetchone()
self.sync_id = row[0]
return super(Users, self).save(*args, **kwargs)
class Meta:
managed = False
db_table = 'users'
unique_together = (('email'),)
查看:
def users_detail_email(request, email):
try:
users = Users.objects.filter(email=email)
except Users.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = UsersSerializer(users, many=True)
return Response(serializer.data)
我已经编写了用于显示用户的所有数据的API代码。但如果找不到它,我需要帮助才能创建它
我尝试在视图中添加以下代码,但它没有保存任何内容
try:
users = Users.objects.filter(email=email)
except Users.DoesNotExist:
context= {"sync_id": 99999999, "points": 0, "phone": "","email": email}
serializer = UsersSerializer(data=context.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
答案 0 :(得分:0)
将字典传递给UserSerializer
:
serializer = UsersSerializer(data=context)
如果你打电话给那些不存在的东西,我就不知道它应该如何工作。你没有带回溯的500错误吗?