How to automatically populate a table field with a foreign key?

Asked

Viewed 473 times

0

Good afternoon! Guys, I made a form where I take the data from this form and send it to two related tables. One of them is the registration table (only with personal information) and another address table (which receives only the address). In the registration table there is an Address field that receives the forign key (Id_end) from the address table.

My problem is: when I fill out the form and send the data to the database, all fields of the tables are filled in, except the field (Address) of the registration table that receives the Foreign key.

I would like this field to be filled AUTOMATICALLY with the (Id_end), which is the primary key, address table. I’ve done a lot of research, but I couldn’t find a solution.

inserir a descrição da imagem aqui

Follow a print of my code where I connect to the database and send the information obtained by the form.

inserir a descrição da imagem aqui

2 answers

1


Friend, when you do an Insert in the database, the database returns some data of that insertion, one of them is the ID that has just been inserted, so you can recover the ID that was inserted in the table endereço and use it in the table’s Insert cadastro, thus:

//Primeiro realize o insert na tabela endereço normalmente
CadastroDb.cursor.execut('seu insert da tabela endereço aqui')
CadastroDb.conn.commit()
//agora para pegar o ID que acabou de ser gerado no insert acima
IDEndereco = CadastroDb.cursor.lastrowid
//Aqui coloque o restante das suas variáveis para o insert da tabela cadastro
CadastroDb.cursor.execut('seu insert da tabela cadastro **com o IDEndereco** aqui')
  • Thank you, Murilo. It worked! I was stuck without being able to solve this problem. Thank you so much for your help. Hug.

  • @Célioferreira I’m glad it worked out! If the answer was helpful to you consider branding it as correct to help other people with the same doubt as you!

0

You can create a variable to pick up the object of the address you want. Then pass this object to the Insert in the Foreign key field. An example:

endereco = Endereco.objetcts.get(id=1) #Faça a logica para pegar o endereco correto
...
CadastroDB.objects.create(nome=NOME, rg=RG, ..., Id_End=endereco)

I couldn’t test it here. Then tell me if it worked

  • Good evening, Vinicius! I couldn’t solve, I don’t think I know how to do it. I’m a beginner and I don’t know much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.