Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

671
Visualizações
Django : One to many relationship

I have a question regarding objects modelling. Let's say we have a one to many relationship where an object A instance could have 0 to many linked objects B whereas object B could be linked to one and only one object A (note here object B cannot be created without being linked to an object B). So far I have added a foreign key to object B model, when adding that object I should select an Object A , so far so good. My question now is do I have to also add the object B to object A model on database level? Or should I just do it on API level by creating nested APIs? So that getting object B would be this way :

get : http://localhost/api/objectA/objectB

I hope I was clear explaining my question but to summarize I am not sure if adding a foreign key to represent a : 0.n---->1.1 is enough.

It has been a long time for me that I did not design a database am I using a very old methodology?

Thanks

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

My question now is do I have to also add the object B to object A model on database level?

No. If you constructed a relation like a ForeignKey, you can let Django query in reverse. So if you have two models:

class A(models.Model):
    pass

class B(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)

Then you can obtain all B objects that belong to some A object somea with:

somea.b_set.all()

You can rename the relation in reverse by setting the related_name=… parameter [Django-doc]. So you can specify the relation as:

class A(models.Model):
    pass

class B(models.Model):
    a = models.ForeignKey(
        A,
        related_name='bs',
        on_delete=models.CASCADE
    )

and then query with:

somea.bs.all()
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda