Django相关字段始终仅在生产时抛出完整性错误

时间:2016-01-06 14:21:00

标签: python mysql django postgresql

我的django应用程序中有两个以下型号:

class BaseModel(models.Model):
    """
    Base model
    """
    uuid = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True)
    created = models.DateTimeField(auto_now_add=True, null=True)
    modified = models.DateTimeField(auto_now=True, null=True)

    class Meta:
        abstract = True

class BaseBillingModel(BaseModel):
    """
    Base billing model with owner field and real_owner method (may reffer to  Customer or Profile)
    """
    owner = models.UUIDField() # uuid of Profile OR Customer

    @property
    def real_owner(self):
        if self.type == 'customer':
            return Customer.objects.get(uuid=self.owner)
        if self.type == 'user':
            return Profile.objects.get(uuid=self.owner)

    class Meta:
        abstract = True


class Invoice(BaseBillingModel):
    type = models.CharField(_('Invoice type'), max_length=16,      choices=INVOICE_PAYMENT_TYPES, default='user')
    title = models.CharField(_("Title"), max_length=128, default="")
    description = models.CharField(_("Description"), max_length=512, default="")
    paid = models.BooleanField(_("Paid"), default=False)
    cost = models.DecimalField(_("Total cost"), decimal_places=2, max_digits=10, default=Decimal("0"))
    public = models.BooleanField(default=True)


    def mark_paid(self):
        self.paid = True
        self.save()


class InvoiceItem(BaseModel):
    invoice = models.ForeignKey(Invoice, null=True, blank=True)
    cost = models.DecimalField(_("Cost"), decimal_places=2, max_digits=10, default=Decimal("0"))
    quantity = models.IntegerField(_("Quantity"), default=1)
    title = models.CharField(_("Title"), max_length=128, default="")
    description = models.CharField(_("Description"), max_length=512, default="")

它基本上是一张包含许多发票项目的发票模型。 我使用formsets动态添加/删除发票中的项目。 当我发布网络表单时,我会迭代项目并总结总成本,然后保存发票。

查看代码:

if request.method == 'POST':
    invoice_form = InvoiceForm(request.POST)
    formset = InvoiceItemFormset(request.POST)

    total_forms = int(request.POST.get('form-TOTAL_FORMS'))

    for x in range(total_forms):
        identifier = "form-{x}-DELETE".format(x=x)
        if identifier in request.POST:
            deleted_items.append(x)


    if request.POST.get('type') == 'customer':
        invoice_form.fields['owner_choice'].choices = [(o.uuid.urn[9:],o.company_name) for o in Customer.objects.filter()]

    if invoice_form.is_valid() and formset.is_valid():
        invoice = invoice_form.save(commit=False)
        invoice.owner = invoice_form.cleaned_data.get('owner_choice')
        cost = Decimal(0)
        for form in formset:

            if form not in formset.deleted_forms:
                item = form.save(commit=False)
                item.invoice = invoice
                item.save()
                cost += item.cost * item.quantity
        invoice.cost = cost
        invoice.save()

它在我的本地环境( MariaDB )上正常工作,正在使用所有项目创建发票。 但是,在舞台/制作服务器上,如果我使用 MySQL PostgreSQL 并不重要 - 我总是会收到如下错误: (PostgreSQL的)

IntegrityError at /staff/billing/new_invoice
insert or update on table "core_invoiceitem" violates foreign key constraint "core_invoiceit_invoice_id_165c623e80fbe59c_fk_core_invoice_uuid"
DETAILS:  Key (invoice_id)=(bb83ff7a-9428-458c-909f-6ab4fa24a1b3) is not present in table "core_invoice".

我不知道如何解决这个问题。任何想法的家伙?

1 个答案:

答案 0 :(得分:0)

在保存发票项目之前,必须先保存其引用的发票。目前,您的阶段/生产服务器在保存发票项目之后但在保存发票之前检查外键约束,因此您会收到完整性错误。

由于您使用的是uuid字段,因此Python正在创建主键而不是数据库。因此,您可以通过使用原子装饰器来防止错误。当您使用atomic装饰器时,数据库会检查原子块末尾的外键约束,这时保存了发票。

from django.db import transaction

transaction.atomic()
def my_view(request):

如果这不起作用,您需要确保在保存发票项目之前保存了发票(没有commit=False)。您可以保存发票项目和发票表单(均为commit=False),计算成本,保存发票,最后保存发票项目。