获取保存在 Django 中的对象的 ID forms.Form

get id of object saved in django forms.Form

models.py:

class Invoice(models.Model):
    invoice_issued_on = models.DateField()

forms.py:

class InvoiceForm(forms.Form):
    invoice_issued_on = forms.DateField(
        input_formats=['%d/%m/%Y'],
        initial=today.strftime("%d/%m/%Y"),
        label=mark_safe('Issued on'),
        widget=forms.TextInput(attrs={ 'placeholder': 'DD/MM/YYYY', 'data-date-format':'DD/MM/YYYY', 'class': 'form-control text-center' })
    )

    def save(self):
        data = self.cleaned_data
        invoice=Invoice(invoice_issued_on=data['invoice_issued_on'])
        instance=invoice.save()

问题: 如何获取保存在数据库中的 Invoice 对象的 ID(数据库 ID)?警告我没有使用 forms.ModelForm 所以 instance.id 在这里不起作用。由于技术原因,我无法使用 ModelForm。

invoice.save()不要return实例。您应该从 invoice 变量中得到 pk

def save(self):
    data = self.cleaned_data
    invoice = Invoice(invoice_issued_on=data['invoice_issued_on'])
    invoice.save()
    return invoice  # invoice.pk will contain id of the object

顺便说一句,对象创建的版本要短得多:

def save(self):
    data = self.cleaned_data
    return Invoice.objects.create(invoice_issued_on=data['invoice_issued_on'])