为什么我无法向 Django 模型的对象添加数据

Why am I unable to add data to django Model's objects

所以这有点奇怪。我从我正在处理的网站发出 post 请求,我在后端获取了数据,但我无法使用接收到的数据访问模型的字段。

我的Models.py:

class Records(models.Model):
    user = models.ForeignKey(Teacher, null=True, on_delete= models.SET_NULL)
    Year = models.CharField(max_length=100, null=True) 
    January = models.CharField(max_length=100, null=True)
    Feburary = models.CharField(max_length=100, null=True)
    March = models.CharField(max_length=100, null=True)
    April = models.CharField(max_length=100, null=True)
    May = models.CharField(max_length=100, null=True)
    June = models.CharField(max_length=100, null=True)
    July = models.CharField(max_length=100, null=True)
    August = models.CharField(max_length=100, null=True)
    September = models.CharField(max_length=100, null=True)
    October = models.CharField(max_length=100, null=True)
    November = models.CharField(max_length=100, null=True)
    December = models.CharField(max_length=100, null=True)

我的Views.py:

@api_view(['POST'])
def Attendance(request):
    data = request.data['list']
    
    print (data)
    
    user = Teacher.objects.get(name=data[0].split('-')[0])
    
    record = Records.objects.get(user=user, Year=data[0].split('-')[1]) 
    
    month = data[1]
    
    print(month)  # output is January
    
    return JsonResponse({'success':True})

所以现在当我尝试打印记录模型的 January 字段时, 我喜欢 print(record.January)

我面临的问题是我做不到record.month 即使月代表一月

我想将从 post 请求中获得的数据添加到模型字段中, 通常我做的是:

record = Records.objects.get(user=user)

record.January = "50"

record.save()

但如前所述,record.month 不起作用,而是我收到此错误:

AttributeError: 'Records' object has no attribute 'month'

我做错了什么?有没有其他方法可以做到这一点?

因为'January'是一个字符串,不能用字符串调用方法。但是你可以设置它:

record.January = '50'

# is the same as:

month = 'January'
setattr(record, month, '50')
# or
setattr(record, 'January', '50')

并在需要时获取此类属性:

month_of_record_value = getattr(record, month)

基本上是将month变量的字符串值翻译成记录的字段名。