更新request.POST中传递的django模型中的字段集

时间:2016-09-26 18:27:13

标签: django

这是我的Model类

class SubJobs(models.Model):
    id = models.AutoField(primary_key = True)
    subjob_name = models.CharField(max_length=32,help_text="Enter subjob name")
    subjobtype = models.ForeignKey(SubjobType)
    jobstatus = models.ForeignKey(JobStatus, default= None, null=True)
    rerun = models.ForeignKey(ReRun,help_text="Rerun")
    transfer_method = models.ForeignKey(TransferMethod,help_text="Select transfer method")
    priority = models.ForeignKey(Priority,help_text="Select priority")
    suitefiles = models.ForeignKey(SuiteFiles,help_text="Suite file",default=None,null=True)
    topofiles = models.ForeignKey(TopoFiles,help_text="Topo file",default=None,null=True)
    load_image = models.NullBooleanField(default = True,help_text="Load image")
    description = models.TextField(help_text="Enter description",null=True)                           command = models.TextField(help_text="Command",null=True)
    run_id = models.IntegerField(help_text="run_id",null=True)
    pid_of_run = models.IntegerField(help_text="pid_of_run",null=True)
    hold_time = models.IntegerField()
    created = models.DateTimeField(default=timezone.now,null=True)
    updated = models.DateTimeField(default=timezone.now,null=True)
    finished = models.DateTimeField(null=True)

用户可能想要更新条目,并可能选择仅更新其中的少数字段。如何编写只更新传递的字段的通用更新语句?

我试过了。

def update_subjob(request):
if (request.method == 'POST'):
    subjobs_subjobid = request.POST[('subjob_id')]
    post_data = request.POST
    if 'subjob_name' in post_data:
        subjobs_subjobname = request.POST[('subjob_name')]
    if 'subjob_type' in post_data:
        subjobs_subjobtype = request.POST[('subjob_type')]
    if 'rerun_id' in post_data:
        subjobs_rerun_id = request.POST[('rerun_id')]
    if 'priority_id' in post_data:
        subjobs_priority_id = request.POST[('priority_id')]
    if 'transfer_method' in post_data:
        subjobs_transfermethod = request.POST[('transfer_method')]
    if 'suitefile' in post_data:
        subjob_suitefile = request.POST[('suitefile')]
    if 'topofile' in post_data:
        subjob_topofile = request.POST[('topofile')]
    try:
        subjobinstance = SubJobs.objects.filter(id=subjobs_subjobid).update(subjob_name=subjobs_subjobname,
                                 updated=datetime.now())

    except Exception as e:
        print("PROBLEM UPDAING SubJob!!!!")
        print(e.message)

如何编写通用更新以仅更新request.POST中发送的字段?

1 个答案:

答案 0 :(得分:1)

你最好使用Forms。但如果你坚持你的代码就可以这样做。

假设您有变量UIStepper,其中列出了您在请求中等待的每个字段。

[indexPath.row].listItemWeight