Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

663
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda