如何以 Django 形式更新记录和在其他 table 中创建的相同记录

how to update record and same record create in other table in django form

我有 2 个模型,一个是 Tempdriver,另一个是 Hiring, 我正在 Tempdriver table 中注册新客户,我在编辑 tempdriver 记录和状态时需要 是(接受),当我保存此记录时,需要在招聘 table 时创建相同的记录,匹配​​列的状态=(已应用于应用程序)其余列在招聘时应为空 table

models.py

class Tempdriver(BaseModel):
    name = models.CharField(max_length=255)
    mobile = models.CharField(max_length=20,unique=True,null=True, blank=True)
    alternate_number = models.CharField(max_length=20, null=True, blank=True)
    date = models.DateField(null=True, blank=True)
    address = models.CharField(max_length=200, null=True, blank=True)
    status = EnumField(choices=['Accept','Reject','Hold'], null=True)

class Hiring(BaseModel):

    STATUS_CHOICES = (('', 'Type...'),
                      ('HR Interview Pass', 'HR Interview Pass'),
                      ('HR Interview Fail', 'HR Interview Fail'),
                      ('Allocation Completed', 'Allocation Completed'),
                      ('Applied on app','Applied on app')
                      )

    
    name = models.CharField(max_length=254, null=True, blank=True)
    mobile = models.CharField(max_length=20,unique=True,null=True, blank=True)
    city = models.ForeignKey(City, models.CASCADE, verbose_name='City', null=True, blank=True)
    age = models.PositiveIntegerField(null=True, blank=True)
    status = models.CharField(max_length = 255,choices=STATUS_CHOICES, null=True, blank=True)

forms.py

class TempDriverForm(forms.ModelForm):
   class Meta:
        model= Tempdriver
        fields='__all__'

views.py

def edit_temp_driver(request,id=0):
    tempdr=Tempdriver.objects.get(pk=id)
    form= TempDriverForm(request.POST or None, request.FILES or None, instance=tempdr)
    if form.is_valid():
        edit = form.save(commit=False)
        edit.save()
        messages.success(request,'Driver data updated successfully!')
        return redirect('/fleet/tempdr')    
    return render(request, 'hiringprocess/edit_tempdriver.html', {'form':form})

首先,让我问一下,为什么你使用 BaseModel 而不是 `models.Model' ?(仅供参考,我只是想在评论中提问,但我不是允许)

如果我正确理解你的问题,你的函数 edit_temp_driver 将是这样的:

def create_hiring_object(form):
    try:
        obj = Hiring()
        obj.name = form.cleaned_data['name']
        obj.mobile = form.cleaned_data['mobile']
        obj.status = obj.STATUS_CHOICES[4]
        obj.save()
    except Exception as err:
        # return error
        return err

def edit_temp_driver(request,id=0):
    tempdr=Tempdriver.objects.get(pk=id)
    form= TempDriverForm(request.POST or None, request.FILES or None, instance=tempdr)
    if form.is_valid():
        edit = form.save(commit=False)
        # call to create hiring 
        create_hiring_object(form)
        edit.save()
        messages.success(request,'Driver data updated successfully!')
        return redirect('/fleet/tempdr')    
    return render(request, 'hiringprocess/edit_tempdriver.html', {'form':form})