Reputation: 8525
To deal with the 2 options (ManyToManyField or ForeignKey) in a project, to be honest, I use the first that comes to my mind.
Let's say we have the following models where a Project can have multiple Assignments.
1st option:
class Project(models.Model):
title = #
class Assignment(models.Model):
project = models.ForeignKey(Project,on_delete=models.CASCADE,
related_name='assignments')
With ForeignKey, when deleting a project, all the assignments related will be also deleted (That's perfect)
2nd option:
class Project(models.Model):
assignments = models.ManyToManyField("Assignment")
class Assignment(models.Model):
# fields
With ManyToManyField, when deleting a project, if I need to delete all the assignments related, I have to use signal
From the point of view of performance and clarity, what is the option opted for?
Upvotes: 0
Views: 40
Reputation: 2223
If you need just one element in your relation you should use ForeignKey that as the same of OneToManyField
If you need many elements from same class related with your object you should go with ManyToMany...
Simple comparison, in django admin ForeignKey render just one select, so you can choice only 1 element by time... while ManyToMany Widget you can select multiple options
Upvotes: 1