How do I insert data into a foreign key table in Django?

Asked

Viewed 251 times

0

class Endereco(models. Model):

cep = models.IntegerField('cep', max_length=10)
rua = models.CharField('rua', max_length=100)
numero = models.CharField('numero', max_length=10)
bairro = models.CharField('bairro', max_length=50)
estado = models.CharField('estado', max_length=50)
cidade = models.CharField('cidade', max_length=50)
usuario = models.ForeignKey('Usuario',on_delete=models.CASCADE, verbose_name='usuario')

1 answer

0

Assuming there is a username user johndoe:

user = User.objects.get(username='johndoe')

In this case, you would create an object of Endereco as follows:

Endereco.objects.create(
    cep='70000000',
    rua='Rua X',
    numero='10',
    bairro='Bairro Y',
    estado='Estado Z',
    cidade='Cidade W',
    usuario=user
)

Browser other questions tagged

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