[Answer]-Relation 1 to N in Django

2👍

class Son: 
    father = models.ForeignKey(Father)

this way any Son can have only one father… however any father can have many son’s, this is a many to one relationship

you can make it better still

class Son:
    father_id = Column(Integer, ForeignKey('father.id'))
    father = relationship("Father", backref="sons")

this will now provide Father instances with a reference named sons that has many sons in a list(not sure why you chose father/son as opposed to parent/child but meh)

-1👍

That’s the best way to do (always define related_name):

class Son(models.Model): 
    father = models.ForeignKey(Father, related_name="sons")

Then you can do:

dad = Father.objects.get(id=5)
for son in dad.sons.all():
     print son.name

Leave a comment