擅长:python、mysql、java
<p>如果一个助理只涉及一个部门,这就是一对多的关系。(一个部门有许多助理)在代码中是:</p>
<pre><code>class Assistant(models.Model):
...
department = models.ForeignKey(Department)
</code></pre>
<p>不需要关于部门的特别参考资料。要获得所有助理:</p>
<pre><code>assistants = models.Assistant.objects.filter(department=department)
</code></pre>
<p>或在类部门上创建属性:</p>
<pre><code>@property
def assistants(self):
return models.Assistant.objects.filter(department=self)
</code></pre>
<p>如果一个助理涉及多个部门(每个部门有多个助理),则是多对多关系,他们之间应该有额外的等级:</p>
<pre><code>class Assignment(models.Model):
assistant = models.ForeignKey(Assistant)
department = models.ForeignKey(Department)
class Department(models.Model):
...
assignment= models.ForeignKey(Assignment)
class Assistant(models.Model):
...
assignment = models.ForeignKey(Assignment)
</code></pre>
<p>因此,在这里查询该部门的助理:</p>
<pre><code>assistants = models.Assistant.objects.filter(
assignment__in=models.Assignment.objects.filter(
department=department
)
)
</code></pre>