Django序列化程序如何将datetime从DB传递到视图“参数必须是9item序列,而不是datetime.datetime”

2024-05-18 07:34:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在模板中使用以下格式设置datetime.datetime

{{ script.lastrundate|date:'Y-m-d' }} {{script.lastrundate|time}}

但是我发现序列化程序生成的值都是字符串,而不是它们的原始类型。当我只是打印它们时,它们是好的;但是如果我想格式化日期,我会得到一个空字符串

我的模型:

class TScript(models.Model):
    id = models.AutoField(primary_key=True)
    category = ForeignKey(TCategory, PROTECT, null=False, blank=False, to_field='name') # protect TScript from deletion; TScript belongs to TCategory
    service = ForeignKey(TService, PROTECT, null=False, blank=False, to_field='name')
    platform = ForeignKey(TPlatform, PROTECT, null=False, blank=False, to_field='name')
    command = models.CharField(max_length=1024, blank=False, null=False)
    machine = models.CharField(max_length=64, blank=False, null=False)
    username = models.CharField(max_length=150, blank=False, null=False) # now save as string to avoid problem
    interval = models.IntegerField(blank=False, null=False) # seconds
    timeout = models.IntegerField(blank=False, null=False) # seconds
    status = models.IntegerField(blank=False, null=False)
    out = models.CharField(max_length=1024, blank=True, null=True)
    error = models.CharField(max_length=512, blank=True, null=True)
    description = models.CharField(max_length=256, blank=True, null=True)
    lastrundate = models.DateTimeField(null=True)
    insertDate = models.DateTimeField(auto_now_add=True)

我的序列化程序:

class TScriptSerializer(serializers.ModelSerializer):
    lastrundate = serializers.DateTimeField() # I changed here but not working
    class Meta:
        model = TScript
        fields = ['id', 'category', 'service', 'platform', 
                  'command', 'machine', 'username', 'interval',
                  'out', 'error', 'timeout', 'status', 'description',
                  'lastrundate', 'insertDate']

我的观点和方法:

@login_required
@csrf_protect
def scriptsList(request):
    logger.info("SCRIPTSLIST Start HTML")
    try:
        scripts=operationsDB.getScripts()
        return render(request, 'tablescripts.html', {"scripts":scripts})
    except Exception as e:
        tb = traceback.format_exc(1)
        logger.error('ERROR Exception in scriptsList, the error is: ' + repr(e) + " - args - " + repr(tb))
        errorMsg="Exception "+repr(e)
        result={"CausesError":errorMsg}
        return redirect('/scriptsList/?' + urllib.urlencode(result))

operationsDB.getScripts()

def getScripts():
    arrScripts=[]
    try:
        scripts=TScript.objects.all()
        for script in scripts:
            serializedScript=TScriptSerializer(script)
            dataScript=serializedScript.data
            arrScripts.append(dataScript)
        return scripts
    except Exception as e:
        tb = traceback.format_exc(1)
        logger.error('ERROR Exception in getScripts; the error is: ' + repr(e) + " - args - " + repr(tb))
        return []
    return arrScripts

我不明白

编辑:此错误与另一个格式错误的字段有关,因此不相关

错误是:

[12/Mar/2018 17:18:42]  ERROR  [scriptsList] - ERROR Exception in scriptsList, the error is: TypeError('argument must be 9-item sequence, not datetime.datetime',) - args - 'Traceback (most recent call last):\n  File "/var/www/html/ElasticSearch/frontEnd/views.py", line 876, in scriptsList\n    return render(request, \'tablescripts.html\', {"scripts":scripts})\nTypeError: argument must be 9-item sequence, not datetime.datetime\n'


Tags: falsetruedatetimereturnmodelsexceptionscriptserror