获取django forms.Form中保存的对象的id

时间:2015-01-08 11:37:08

标签: python django

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。

1 个答案:

答案 0 :(得分:1)

invoice.save()不返回实例。您应该从pk变量

获得invoice
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'])