我有两个模特,公司和合同。每份合同都在两家公司之间。现在,似乎公司和合同之间存在ManyToMany关系,例如公司可以签订多份合同,合同可以在多家公司之间签订。它是否正确?如果是的话,如何在Django中指定?它是通过一个模型中的两个外键吗?
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)
答案 0 :(得分:3)
如果合同只在两家公司之间,那么就删除这一行。您的合同模型对公司有两个不同的外键字段这一事实已经暗示合同只在两家公司之间,并且每家公司可能通过使用相应的相关名称来访问多个合同。
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)
但是,如果您想要一份涉及两家以上公司的合同,那么您将删除这两个外国钥匙,并使用像这样的多种关系。同样,这将自动暗示特定合同由该关系下列出的所有公司共享。您也可以通过其related_name访问特定公司的合同。
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)