两个Django模型在一个视图中使用外键

时间:2013-07-15 20:49:58

标签: django django-models

我从Django开始。我有3个模型,一个父类“Cliente”和两个子类,“Persona”和“Empresa”。 models.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”。你能救我吗?

1 个答案:

答案 0 :(得分:1)

文档Here中有一个很好的例子。

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

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,
    })