调用save()后没有保存Django模型?

时间:2016-06-11 23:14:52

标签: django django-forms

我覆盖了ModelForm的保存方法。我正在解析Excel文件,如果有一些值,我会更新表单实例相关对象中的数量。当实例没有相关对象时,它第一次工作。但第二次,当我更新值时,没有任何反应。我不确定它是否与commit参数有关。

编辑 - 相关代码:

def save(self, commit=True):
    """
    Overrides the save method in order to add the product inventory items listed in
    the uploaded Excel file, if one was uploaded.
    """
    inventory = super(AddOrChangeProductsInventoryForm, self).save(commit)

    self._update_inventory_items_quantities()

    if not commit:
        inventory.save()
        self.save_m2m()

    return inventory

def _update_inventory_items_quantities(self):
    inventory = self.instance

    if len(self.excel_data_dict) == 0:
        return inventory

    non_existing_products = []

    for i, product_sku in enumerate(self.excel_data_dict['SKU']):
        quantity = self.excel_data_dict['Cantidad'][i]
        new_item = inventory.productinventoryitem_set.filter(product__sku=product_sku).first()

        if new_item is None:
            product = Product.objects.filter(sku=product_sku).first()

            if product is None:
                # TODO: Raise warning in view
                non_existing_products.append(product_sku)
                continue

            new_item = ProductInventoryItem()
            new_item.product = product
            new_item.inventory = inventory

        new_item.quantity += quantity
        # TODO: Check why after first update it's not being updated

2 个答案:

答案 0 :(得分:0)

如果您的模型具有任意多对多关系,那么您需要确保并将self.save_m2m()与save方法结合使用。这是一个简单的例子:

# save method of your forms.ModelForm class.
def save(self):
    obj = super(MyModelForm, self).save(commit=False)
    obj.save()
    self.save_m2m()
    return obj

答案 1 :(得分:0)

当提交为False时,您正在保存表单。 替换(第10行):

if not commit:

使用:

if commit:

<强>更新

new_iteminventory.productinventoryitem_set.filter(product__sku=product_sku).first()

的新副本

ProductInventoryItem()

它是局部变量,不会更新inventory。执行该功能后,所有这些更改都将被破坏。您需要在inventory

中存储更改

当你覆盖_save_m2m时:

for obj in self.instance.productinventoryitem_set.all(): 
    obj.quantity += 2 
    obj.save()

然后在销毁之前保存更改。

您可以这样做:

def save(self, commit=True):

    inventory = super(AddOrChangeProductsInventoryForm, self).save(commit)

    self._update_inventory_items_quantities(inventory, commit)

    return inventory

def _update_inventory_items_quantities(self, inventory, commit):

    if len(self.excel_data_dict) == 0:
        return inventory

    non_existing_products = []

    for i, product_sku in enumerate(self.excel_data_dict['SKU']):
        quantity = self.excel_data_dict['Cantidad'][i]
        new_item = inventory.productinventoryitem_set.filter(product__sku=product_sku).first()

        if new_item is None:
            product = Product.objects.filter(sku=product_sku).first()

            if product is None:
                # TODO: Raise warning in view
                non_existing_products.append(product_sku)
                continue

            new_item = ProductInventoryItem()
            new_item.product = product
            new_item.inventory = inventory

        new_item.quantity += quantity
        if commit:
            new_item.save()