Home > Enterprise >  Django : One to many relationship
Django : One to many relationship

Time:11-28

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

CodePudding user response:

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()
  • Related