0

这是进行备份和更新原始文件的明智方法吗?

    project = Project.objects.get(pk=project_id)                  
# ...
    if request.method == "POST": # If the form has been submitted...           
        project_form = ProjectForm(request.POST, instance=project)
        if  project_form.is_valid():
            project.save(force_insert=True)    # Make a backup copy

            updated_project = project_form.save(commit=False)
            updated_project.editor_id = editor_id
            if request.POST["beginyear"]:  by = int(request.POST["beginyear"])
            if request.POST["beginmonth"]: bm = int(request.POST["beginmonth"])
            if (by > 0) and (bm > 0):
                updated_project.begin_date = "%4.4d-%2.2d-01" % (by,bm,)
# ...
            updated_project.save()
4

1 回答 1

3

Is it working at all? I am asking if copy is properly saved, because for me it looks it doesn't: force_insert does what it says actually - it just makes INSERT request instead of UPDATE in SQL. What you need is to make copy - you can do it like that:

project.pk = None
project.save()

I would also refactor it a little bit if you don't mind:

by = request.POST.get("beginyear")
bm = request.POST.get("beginmonth")
if by and bm:
    try:
        updated_project.begin_date = datetime.datetime(year=int(by), month=int(bm), day=1)
    except ValueError:
       #some handling here
       pass

So now you don't have to initialize by and bm and I think it is more obvious what it does now.

于 2012-08-29T21:38:57.673 回答