使用 Django .update() 和 .get()
Using Django .update() with .get()
我有发票table
# app/models.py
class tbl_invoice(models.Model):
invoice_id = models.IntegerField(blank=True, null=True)
invoice_number = models.IntegerField(blank=True, null=True)
quotation_id = models.IntegerField(blank=True, null=True)
quotation_number = models.IntegerField(blank=True, null=True)
invoiced = models.CharField(max_length=50, default='', blank=True, null=True)
此table包含发票和报价记录,系统用户可以选择将任何报价转换为发票,但报价记录仍将与新生成的发票记录一起保留
这是我的看法
#views.py
obj = tbl_invoice.objects.get(pk='someId') # getting existing record with pk
obj.pk = None
obj.invoice_id = 'someId'
obj.quotation_id = None
obj.invoice_number = 'someValue'
obj.quotation_number = None
obj.invoiced = 'no'
obj.type_status = 'invoice'
obj.save()
上面的代码工作正常,它创建了一个新的发票记录并维护了旧的报价记录
然而,在将报价单转换为发票后,我还想将报价记录中的 invoiced
值更新为 yes
为此,我尝试了
obj.update(invoiced = 'yes')
但 .update()
不适用于 .get()
如何从现有记录创建新记录并同时更新旧记录
还是我必须使用多个查询
感谢您的帮助。
简单地说,
old_obj = tbl_invoice.objects.get(pk='someId') # getting existing record with pk
# creating new object
new_obj = old_obj
# altering new object values
new_obj.pk = None
new_obj.invoice_id = 'someId'
new_obj.quotation_id = None
new_obj.invoice_number = 'someValue'
new_obj.quotation_number = None
new_obj.invoiced = 'no'
new_obj.type_status = 'invoice'
# altering old object value
old_obj.invoiced = "yes"
# saving objects
new_obj.save()
old_obj.save()
我有发票table
# app/models.py
class tbl_invoice(models.Model):
invoice_id = models.IntegerField(blank=True, null=True)
invoice_number = models.IntegerField(blank=True, null=True)
quotation_id = models.IntegerField(blank=True, null=True)
quotation_number = models.IntegerField(blank=True, null=True)
invoiced = models.CharField(max_length=50, default='', blank=True, null=True)
此table包含发票和报价记录,系统用户可以选择将任何报价转换为发票,但报价记录仍将与新生成的发票记录一起保留
这是我的看法
#views.py
obj = tbl_invoice.objects.get(pk='someId') # getting existing record with pk
obj.pk = None
obj.invoice_id = 'someId'
obj.quotation_id = None
obj.invoice_number = 'someValue'
obj.quotation_number = None
obj.invoiced = 'no'
obj.type_status = 'invoice'
obj.save()
上面的代码工作正常,它创建了一个新的发票记录并维护了旧的报价记录
然而,在将报价单转换为发票后,我还想将报价记录中的 invoiced
值更新为 yes
为此,我尝试了
obj.update(invoiced = 'yes')
但 .update()
不适用于 .get()
如何从现有记录创建新记录并同时更新旧记录 还是我必须使用多个查询
感谢您的帮助。
简单地说,
old_obj = tbl_invoice.objects.get(pk='someId') # getting existing record with pk
# creating new object
new_obj = old_obj
# altering new object values
new_obj.pk = None
new_obj.invoice_id = 'someId'
new_obj.quotation_id = None
new_obj.invoice_number = 'someValue'
new_obj.quotation_number = None
new_obj.invoiced = 'no'
new_obj.type_status = 'invoice'
# altering old object value
old_obj.invoiced = "yes"
# saving objects
new_obj.save()
old_obj.save()