[英]Django model relation
I'm making the model for my app and I have a question about the relationship of a model. 我正在为我的应用程序制作模型,我对模型的关系有疑问。
The Company model has one or more Offices. 公司模型有一个或多个主管局。 And the Office has one or more Employees.
该办公室有一名或多名雇员。
class Company(models.Model):
name = models.CharField(max_length=50)
mail = models.EmailField(null=True, blank=True)
NIF = models.CharField(max_length=9, null=True, blank=True)
def __unicode__(self):
return self.name
class Office(models.Model):
company = models.ForeignKey(Company)
name = models.CharField(max_length=50, default='Main')
direction = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class Employee(models.Model):
company = models.ForeignKey(Company)
office = models.ForeignKey(Office)
name = models.CharField(max_length=50)
mail = models.EmailField(null=True, blank=True)
def __unicode__(self):
return self.name
How I can make a relationship between the employee and the company and office? 我如何才能在员工与公司和办公室之间建立关系?
Remove the company
foreign key from Employee
. 从
Employee
删除company
外键。
class Employee(models.Model):
office = models.ForeignKey(Office)
name = models.CharField(max_length=50)
mail = models.EmailField(null=True, blank=True)
def __unicode__(self):
return self.name
As the Office
model already has a relationship with Company
and Employee
has relationship to Office
, you can just access it like employee.office.company
- 随着
Office
模式已经有关系Company
和Employee
有关系的Office
,你可以访问它像employee.office.company
-
employee_one = Employee.objects.get(pk=1)
company_of_employee_one = employee_one.office.company
If you want to access the data other way around(ie get all offices of a company, get all employees of an office), you can do something like this - 如果您想以其他方式访问数据(即获取公司的所有办公室,获得办公室的所有员工),您可以执行以下操作 -
company = Company.objects.get(pk=1)
offices = company.office_set.all()
for office in offices:
employees = office.employee_set.all()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.