序列化器-Django REST Framework-序列化器字段的名称可能不正确,并且与`str`实例上的任何属性或键都不匹配

时间:2018-12-03 07:10:50

标签: django serialization django-serializer

我想像下面的例子一样完全填充chartJs:https://www.chartjs.org/docs/latest/charts/bar.html

我收到此错误:

AttributeError at /timesheet/json-month/
Got AttributeError when attempting to get a value for field `working_hour` on serializer `TimesheetSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `str` instance.
Original exception text was: 'str' object has no attribute 'working_hour'.

使用此模型:

class Timesheet(models.Model):
    owner = models.ForeignKey(User, on_delete = models.CASCADE)
    title = models.CharField(max_length = 64, verbose_name = _("Title"))
    date = models.DateField(default=datetime.datetime.now())
    working_hour = models.FloatField(verbose_name = _("Working time"))
    week = models.IntegerField(verbose_name = "working week")

    def __str__(self):
        return "{}".format(self.title)

    def save(self, *args, **kwargs):
        if not self.pk:
            self.week = datetime.datetime.strptime("{}".format(self.date), "%Y-%m-%d").isocalendar()[1]
        super(Timesheet, self).save(*args, **kwargs)

我这样序列化数据(进入我的视图):

def get_month_hours(self):
    cursor = connection.cursor()
    cursor.execute("""
        SELECT 
            MONTH(date),
            SUM(working_hour)
        FROM
            timesheet_timesheet
        WHERE
            owner_id = %s
        AND
            date >= MONTH(CURRENT_TIMESTAMP) - 12
        GROUP BY
            MONTH(date)
    """, [self.user])
    row = cursor.fetchone()[0]
    return str(row)

@api_view(['GET'])
def timesheet_total_per_month(request):
    hours = ReturnHour(request.user.pk, datetime.datetime.now().isocalendar()[1])
    timesheets = hours.get_month_hours()
    serializer = TimesheetSerializer(timesheets, many=True, read_only = True)
    return Response(serializer.data)

进入我的serializers.py:

class TimesheetSerializer(serializers.ModelSerializer):
class Meta:
    model = Timesheet
    fields ='__all__'

def create(self, validated_data):
    """
    Create and return a new `Snippet` instance, given the validated data.
    """
    return Timesheet.objects.create(**validated_data)

def update(self, instance, validated_data):
    instance.owner = validated_data.get('owner_id', instance.owner)
    instance.date = validated_data.get('date', instance.date)
    instance.title = validated_data.get('title', instance.title)
    instance.working_hour = validated_data.get('working_hour', instance.working_hour)
    return instance

你知道原因吗?

每笔预付款

2 个答案:

答案 0 :(得分:1)

在我看来,您的方法get_month_hours返回的是字符串,这就是DRF无法对其进行序列化的原因。您需要从该方法返回queryset。您可以尝试这样:

import datetime
from django.db.models import Sum

def get_month_hours(self):
   last_year = timezone.now() - datetime.timedelta(days=365)  # for more accurate result, please use python-dateutil or similar tools

    return TimeSheet.objects.filter(owner=self.user, date__gte=last_year).annotate('total_hour'=Sum('working_hour')).order_by('date')

答案 1 :(得分:0)

我有类似的问题,只是您问题中的'str'实例是我的模型名称。 我在视图集中使用了错误的序列化程序,即

class X_ViewSet(viewsets.ModelViewSet):
    serializer_class = Xserilizer
    #serializer_class = Yserializer

    def get_queryset(self):
        return Mmodel.objects.all()