Reputation: 1313
I have two models, company and contract. Each contract is between two companies. Now, it seems there is a ManyToMany relationship between company and contract, e.g. a company can have many contracts and a contract is between more than one company. Is this correct? If yes, how to do you specify that in Django? Is it through two foreign keys in one model?
class Company(models.Model):
company_name = models.CharField(max_length = 30)
address = models.CharField(max_length = 100)
website = models.CharField(max_length = 30)
email = models.EmailField(max_length = 30)
class Contract(models.Model):
company_1 = models.ForeignKey(Company, related_name="%(app_label)s_%(class)s_related_company1")
company_2 = models.ForeignKey(Company, related_name="%(app_label)s_%(class)s_related_company2")
company = models.ManyToManyField(Company)
contract_date = models.DateField()
consideration = models.DecimalField(max_digit =10, decimal_places = 2)
Upvotes: 0
Views: 975
Reputation: 1497
If a contract is just between two companies, then just remove this line. The mere fact that your Contract model has two different foreign key fields to Company already imply that a contract is between only two companies and each company may have multiple contracts accessible by using the respective related_name's.
class Contract(models.Model):
company_1 = models.ForeignKey(Company, related_name="%(app_label)s_%(class)s_related_company1")
company_2 = models.ForeignKey(Company, related_name="%(app_label)s_%(class)s_related_company2")
# company = models.ManyToManyField(Company)
contract_date = models.DateField()
consideration = models.DecimalField(max_digit =10, decimal_places = 2)
If, however, you want a contract involving more than two companies, then you remove the two foreignkeys and use a manytomany relationship like so. Similarly, this will automatically imply that a particular contract is shared by all companies listed under that relationship. You may access the contracts of a particular company via its related_name as well.
class Contract(models.Model):
# company_1 = models.ForeignKey(Company, related_name="%(app_label)s_%(class)s_related_company1")
# company_2 = models.ForeignKey(Company, related_name="%(app_label)s_%(class)s_related_company2")
companies = models.ManyToManyField(Company, related_name=whatever_you_want)
contract_date = models.DateField()
consideration = models.DecimalField(max_digit =10, decimal_places = 2)
Upvotes: 5