本文介绍了序列化器-Django REST Framework-序列化器字段的名称可能不正确,并且与`str`实例上的任何属性或键都不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想像示例一样填充chartJs: https://www.chartjs.org/docs/latest/charts/bar.html

I want to populate a chartJs exactly like the example: 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)

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

I serialize my data like that (into my view):

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:

Into my 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

你知道原因吗?

对每笔预付款表示感谢,

thanks per advance,

推荐答案

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

It seems to me that your method get_month_hours is returning string, that is why DRF is not able to serialize it. You need to return queryset from that method. You can try like this:

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')

这篇关于序列化器-Django REST Framework-序列化器字段的名称可能不正确,并且与`str`实例上的任何属性或键都不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 21:34