模型之间的关系(Django)

时间:2018-02-01 22:39:16

标签: python django django-models

我有2个型号 venta和detalleventa 这很好,因为销售可以有很多细节

class Venta(models.Model):
cliente = models.ForeignKey(Cliente,on_delete=models.CASCADE,verbose_name='Cliente')
fecha =  models.DateField(auto_now_add=True)
descripcion = models.CharField(max_length=300, blank=True, verbose_name='Detalle del pedido')
total = models.DecimalField(decimal_places=2, max_digits=7, verbose_name='Total de la venta')

def __str__(self):
    return '{}'.format(self.id)

class DetalleVenta(models.Model):
producto = models.ForeignKey(Producto,on_delete=models.CASCADE,verbose_name='Producto')
cantidad = models.IntegerField(verbose_name='Cantidad')
venta = models.ForeignKey(Venta,on_delete=models.CASCADE, verbose_name='Venta')

def __str__(self):
    return '{} - {}'.format(self.venta,self.producto)

如果外键有detalle,我如何访问venta的详细信息? 因为如果有几个detalles你不应该编辑一个一个,如果你不编辑包含所有detalles的venta

到目前为止,我可以编辑,但通过它的detalle:

class VentaUpdate(UpdateView):
model = DetalleVenta
second_model = Venta
template_name = 'venta/venta_form.html'
form_class = DetalleForm
second_form_class = VentaForm
success_url = reverse_lazy('venta:ventas_listar')

def get_context_data(self, **kwargs):
    context = super(VentaUpdate, self).get_context_data(**kwargs)
    pk = self.kwargs.get('pk', 0)
    detalle = self.model.objects.get(id=pk)
    venta = self.second_model.objects.get(id=detalle.venta_id)
    if 'form' not in context:
        context['form'] = self.form_class()
    if 'form2' not in context:
        context['form2'] = self.second_form_class(instance=venta)
    context['id'] = pk
    return context

def post(self, request, *args, **kwargs):
    self.object = self.get_object
    id_detalle = kwargs['pk']
    detalle = self.model.objects.get(id=id_detalle)
    venta = self.second_model.objects.get(id=detalle.venta_id)
    form = self.form_class(request.POST, instance=detalle)
    form2 = self.second_form_class(request.POST, instance=venta)
    if form.is_valid() and form2.is_valid():
        form.save()
        form2.save()
        return HttpResponseRedirect(self.get_success_url())
    else:
        return HttpResponseRedirect(self.get_success_url())

它有效,但想法是编辑一个venta而不是一个detalle

0 个答案:

没有答案