无法分配必须是一个实例

时间:2015-12-22 01:07:21

标签: python django

我想在2个表中插入:CostItems和CostElements,CostElements将cost_item作为CostItems的外键,但是当我运行它时会显示以下错误消息:

  

无法指定“22”:“CostElements.cost_item”必须是“CostItems”   实例

Heres是我的代码:

Models.py:

class CostItems(ModelAudit):
    cost_item = models.AutoField(primary_key = True, verbose_name = 'Item de costo')
    group = models.ForeignKey(Groups, verbose_name = 'Grupo')
    description = models.CharField(max_length = 100, verbose_name =' Descripcion')
    usd_value = models.IntegerField(verbose_name ='Valor en USD')
    rer = models.IntegerField(verbose_name = 'TRM')
    pesos_value = models.IntegerField(verbose_name = 'Valor en pesos')
    supplier = models.ForeignKey(Suppliers, verbose_name = 'Proveedor')
    position = models.ForeignKey(Positions, verbose_name = 'Cargo')
    observations = models.TextField(max_length = 500, verbose_name = 'Observación')
    validity_date = models.DateField(verbose_name = 'Fecha de vigencia')

class CostElements(ModelAudit):
    cost_element = models.AutoField(primary_key = True, verbose_name = 'Elemento de costo')
    cost_item = models.ForeignKey(CostItems, verbose_name = 'Item de costo')
    description = models.CharField(max_length = 100, verbose_name = 'Descripción')
    usd_value = models.IntegerField(verbose_name = 'Valor en USD')
    pesos_value = models.IntegerField(verbose_name = 'Valor en pesos')
    percent = models.IntegerField(verbose_name = 'Porcentaje de peso')

Views.py:

class CostItemInsert(View):
    template_name='cost_control_app/home.html'

    def post(self, request, *args, **kwargs):
        if request.user.has_perm('cost_control_app.add_costitems'):
            form_insert = CostItemsForm(request.POST)
            if form_insert.is_valid():
                form_save = form_insert.save(commit = False)
                #import pdb; pdb.set_trace()
                des = form_save.description,
                usd = form_save.usd_value,
                pes = form_save.pesos_value,
                form_save.save(force_insert = True) 
                ci= get_object_or_404(CostItems, cost_item=form_save.cost_item)
                cost_element_created = CostElements.objects.create(
                            description = des,
                            percent = 100,
                            usd_value = usd,
                            pesos_value = pes,
                            cost_item = ci.cost_item
                        )

                messages.success(request, "Item de costo creado con exíto")
                return HttpResponseRedirect(reverse('cost_control_app:cost_item'))   
            else:
                messages.error(request, "No se pudo guardar el registro")
                return render(request, self.template_name,{
                                                            "form_cost_item":form_insert,
                                                          })
        else:
            messages.error(request, "No tienes permisos para esta acción")
            return HttpResponseRedirect(reverse('cost_control_app:home'))

22在form_save.save(force_insert = true)之后已经创建了CostItem ID,我不知道它为什么不起作用,请帮助!!

2 个答案:

答案 0 :(得分:2)

当您使用快捷方式 get_object_or_404时,根据Docs,返回的对象已经是您正在使用的模型的实例。在这种情况下,CostItems对象。

这意味着您应该使用直接返回的对象 现在您将ci.cost_item作为参数传递。但是,cost_itemCostItems模型中的字段。因此,您将该字段作为参数传递,而不是整个实例。

因此,Django提出了这个错误。如前所述,您应该使用CostItem的整个实例来使代码工作。

您的代码应该是

ci= get_object_or_404(CostItems, cost_item=form_save.cost_item)
cost_element_created = CostElements.objects.create(
                            description = des,
                            percent = 100,
                            usd_value = usd,
                            pesos_value = pes,
                            cost_item = ci)

答案 1 :(得分:0)

解决了它,只是在form_save.save之前取出变量赋值的“comas”并且它起作用了。

谢谢拉斐尔