Django RestFramework错误与POST请求上的DateTimeField序列化程序关联

时间:2016-12-05 16:27:03

标签: python json django serialization

基于下面的Serializer,Mixin和View,我能够通过GET请求成功检索JSON数据(见下文),但我在尝试执行时遇到exec steptest.set(1234); select steptest.get from dual; 通过Django Restframework进行JSON POST,我无法弄清楚原因。请帮忙。我还添加了TransactionDateTime模型和JSON POST请求,它给了我错误。我使用Postman发送请求。提前致谢。我的猜测是我的问题是使用serializers.DateTimeField,因为我使用下面的方法通过Django shell成功插入数据

"AttributeError: 'NoneType' object has no attribute 'request'"

请参阅以下序列化程序,通过生成错误的GET请求,Mixin,View,Model和POSt JSON请求返回的成功JSON。

串行

my_date = datetime.strptime('2015-01-28 05:30:00', '%Y-%m-%d %H:%M:%S')

通过GET请求成功获取JSON数据

class SimpleSerializer4(BulkSerializerMixin, ModelSerializer):

    user = serializers.SerializerMethodField()
    start_dt = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', input_formats=['%Y-%m-%d %H:%M:%S'])   

    def get_user(self, obj):
        test_me = self.context.get('request')
        return test_me


    class Meta(object):
        model = TransactionDateTime
        list_serializer_class = BulkListSerializer
        fields = ('pk','start_dt', 'user')

观点和混合

 [
  {
   "pk": 1,
   "start_dt": "2015-01-28 03:00:00",
   "user": "cdoe"
  },
  {
   "pk": 2,
   "start_dt": "2015-01-28 05:30:00",
   "user": "cdoe"
  }
 ]

TransactionDateTime模型

class DateTimeMixin(object):
    serializer_class = SimpleSerializer4
    permission_classes = (permissions.IsAuthenticated,)


class DateTimeViewSet(DateTimeMixin, generics.BulkModelViewSet):

    def get_queryset(self):

        num = self.kwargs['dt_rm']
        num2 = self.kwargs['id']

        r1 = Room.objects.get(id = num)

        s1 = Schedule.objects.get(pk=num2)
        u= self.request.user.pk
        usr = User.objects.get(pk=u)

        if(s1.user.username == usr.username):
            queryset = r1.transactiondatetime_set.all()
            return queryset
        else: raise Http404("User does not exist")



    def get_serializer_context(self):

        num = self.kwargs['id']
        s1 = Schedule.objects.get(pk=num)
        var = s1.user.username
        context = super(DateTimeViewSet, self).get_serializer_context()
        return {'request' : var}

给我错误的JSON POST请求

 class TransactionDateTime(models.Model):
    room = models.ForeignKey(Room, on_delete = models.CASCADE)
    start_dt = models.DateTimeField('start_dateTime')
    end_dt = models.DateTimeField('end_dateTime', blank=True, null=True)


    def __str__(self):
        return str(self.start_dt)

1 个答案:

答案 0 :(得分:0)

你可以试试这个

我尽量不要覆盖上下文中的请求键工作并返回整个上下文

DateTimeViewSet

def get_serializer_context(self): 
    num = self.kwargs['id'] 
    s1 = Schedule.objects.get(pk=num) 
    var = s1.user.username 
    context = super(DateTimeViewSet, self).get_serializer_context() 
    context['user'] = var
    return context

SimpleSerializer4

def get_user(self, obj): 
    test_me = self.context.get('user') 
    return test_me