gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:50:02 25 4
gpt4 key购买 nike

我想像示例一样填充 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

你知道原因吗?

提前感谢,

最佳答案

我遇到了类似的问题,只是您问题中的“str”实例是我的模型名称。
我在 View 集中使用了错误的序列化程序,即

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

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

关于django - 序列化程序 - Django REST Framework - 序列化程序字段可能命名不正确,并且与 `str` 实例上的任何属性或键都不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53589040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com