我有一个非常愚蠢的问题。所有主键(id)以字符串形式返回,但我需要整数。
https://www.googleapis.com/batch
型号:
Django==2.1.5
djangorestframework==3.9.1
djangorestframework-jsonapi==2.7.0
查看:
class Room(models.Model):
id = models.IntegerField(primary_key=True)
creator = models.ForeignKey(
User,
verbose_name='Creator',
on_delete=models.CASCADE
)
invited = models.ManyToManyField(
User,
verbose_name='Invited',
related_name='invited_user'
)
number_1 = models.IntegerField(
default=1
)
number_2 = models.IntegerField(
default=2
)
number_3 = models.IntegerField(
default=3
)
date = models.DateTimeField('Created at', auto_now_add=True)
class Meta:
verbose_name = 'Chat room'
verbose_name_plural = "Chat rooms"
db_table = 'room'
序列化器:
class Rooms(APIView):
permission_classes = [permissions.IsAuthenticated]
@staticmethod
def get(request):
# rooms = Room.objects.filter(creator=request.user)
rooms = Room.objects.all()
serializer = RoomSerializer(rooms, many=True)
return Response(serializer.data)
请求:
class RoomSerializer(serializers.ModelSerializer):
# id = serializers.IntegerField()
creator = UserSerializer(read_only=True)
invited = UserSerializer(many=True, read_only=True)
class Meta:
id = serializers.IntegerField(label='ID', read_only=True)
model = Room
fields = ['id', 'number_1', 'number_2', 'number_3', 'creator', 'invited', 'date']
在请求室ID和用户ID是字符串,但是我需要整数类型。如果另一个字段的类型为整数(数字_1,数字_2,数字_3),则将其返回为整数。我不知道如何解决。感谢您的帮助
答案 0 :(得分:0)
谢谢大家的帮助,问题出在设置上。起初,我只是复制它们,然后渗透并删除多余的部分。现在他们看起来像这样
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 1,
# 'DEFAULT_PERMISSION_CLASSES': (
# 'rest_framework.permissions.IsAdminUser',
# 'rest_framework.permissions.AllowAny',
# ),
# 'DEFAULT_AUTHENTICATION_CLASSES': (
# # 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
# 'rest_framework.authentication.TokenAuthentication',
# 'rest_framework.authentication.BasicAuthentication',
# 'rest_framework.authentication.SessionAuthentication',
# ),
# 'EXCEPTION_HANDLER': 'rest_framework_json_api.exceptions.exception_handler',
# 'DEFAULT_PARSER_CLASSES': (
# 'rest_framework_json_api.parsers.JSONParser',
# 'rest_framework.parsers.FormParser',
# 'rest_framework.parsers.MultiPartParser'
# ),
# 'DEFAULT_RENDERER_CLASSES': (
# 'rest_framework_json_api.renderers.JSONRenderer',
# 'rest_framework.renderers.BrowsableAPIRenderer',
# ),
# 'DEFAULT_METADATA_CLASS': 'rest_framework_json_api.metadata.JSONAPIMetadata',
}