1

我从 Django 开始。我有 3 个模型,一个父类“Cliente”和两个子类“Persona”和“Empresa”。模型.py

class Cliente(models.Model):
    idcliente = models.AutoField(unique=True, primary_key=True)
    direccion = models.CharField(max_length=45L, blank=True)
    telefono = models.CharField(max_length=45L, blank=True)
    email = models.CharField(max_length=45L, blank=True) 
    def __unicode__(self):
        return u'Id: %s' % (self.idcliente)

    class Meta:
        db_table = 'cliente'

class Empresa(models.Model):
    idcliente = models.ForeignKey('Cliente', db_column='idcliente', primary_key=True)
    cuit = models.CharField(max_length=45L)
    nombre = models.CharField(max_length=60L)
    numero_ingresos_brutos = models.CharField(max_length=45L, blank=True) 
    razon_social = models.CharField(max_length=45L, blank=True)
    def __unicode__(self):
        return u'CUIT: %s - Nombre: %s' % (self.cuit, self.nombre)

    class Meta:
        db_table = 'empresa'

class Persona(models.Model):
    idcliente = models.ForeignKey('Cliente', db_column='idcliente', primary_key=True)
    representante_de = models.ForeignKey('Empresa', null=True, db_column='representante_de', blank=True, related_name='representa_a')
    nombre = models.CharField(max_length=45L)
    apellido = models.CharField(max_length=45L)
    def __unicode__(self):
        return u'Id: %s - Nombre completo: %s %s' % (self.idcliente, self.nombre, self.apellido)

    class Meta:
        db_table = 'persona'

我想在同一个视图中管理一个类及其父级。我想以相同的形式添加、编辑和删除“Cliente”和“Persona”/“Cliente”。你能帮助我吗?

4

1 回答 1

1

此处的文档中有一个很好的示例。

我是根据文档编写的,因此未经测试。

def manage_books(request, client_id):
    client = Cliente.objects.get(pk=client_id)
    EmpresaInlineFormSet = inlineformset_factory(Cliente, Empresa)
    if request.method == "POST":
        formset = EmpresaInlineFormSet(request.POST, request.FILES, instance=author)
        if formset.is_valid():
            formset.save()
            # Do something. Should generally end with a redirect. For example:
            return HttpResponseRedirect(client.get_absolute_url())
    else:
        formset = EmpresaInlineFormSet(instance=client)
    return render_to_response("manage_empresa.html", {
        "formset": formset,
    })
于 2013-07-15T22:39:00.300 回答