Reputation: 991
There are two models Parent and Children.
class Parent(models.Model):
name = models.CharField(max_length=128)
children = ?
class Children(models.Model):
name = models.CharField(max_length=128)
parent = ?
If we need the children instances to have parent as link to model Parent we can use ForeignKey in Children and vice versa.
If parent A has children B and C and we want A to have ids of children B and C and children B and C to have id of parent A. i.e. A.children = (B.id, C.id) and B.parent = A.id, C.parent = A.id.
How can we achieve this?
parent = models.ForeignKey(Parent, related_name='children')
can this be used?
Upvotes: 0
Views: 942
Reputation: 37364
Yes, if a Child
instance has exactly one parent a ForeignKey
field to the parent model is the correct relation. Your example looks fine to me except that the convention is that model names are singular rather than plural - class Child(models.Model):
rather than class Children(models.model):
.
Upvotes: 1