2013-07-15 171 views
1

我從Django開始。我有3個模型,一個父類「Cliente」和兩個子類「Persona」和「Empresa」。 models.py在一個視圖中使用外鍵的兩個Django模型

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」。你可以幫我嗎?

+0

嗨,歡迎來到Stackoverflow!此Q&A網站的主要語言是英語,請問您可以翻譯您的問題嗎? –

+0

當''ForeignKey'具有'primary_key = True'時,請考慮'OneToOneField'。 –

+0

將ForeignKey更改爲OneToOneField可解決此問題。非常感謝! –

回答

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, 
    }) 
相關問題