<p>根据您定义模型的方式,这些查询似乎太令人困惑了。尝试下面如何定义模型,然后尝试查询</p>
<p>您没有在多对多字段定义中提到through_字段属性。检查文档:<a href="https://docs.djangoproject.com/en/3.2/ref/models/fields/#django.db.models.ManyToManyField" rel="nofollow noreferrer">https://docs.djangoproject.com/en/3.2/ref/models/fields/#django.db.models.ManyToManyField</a></p>
<pre class="lang-py prettyprint-override"><code>class Department(models.Model):
# i think this is not needed. Also id is a protected keyword in python.
# id = models.BigAutoField(primary_key=True)
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
assistants = models.ManyToManyField(settings.AUTH_USER_MODEL, through='Assistants',
related_name='departments', through_fields=("department", "assistant"))
# model name should never be prural. It is singluar becuase it is the name of the object.
class Assistant(models.Model):
# i think this is not needed. Also id is a protected keyword in python.
# id = models.BigAutoField(primary_key=True)
department = models.ForeignKey(Department, on_delete=models.CASCADE)
assistant = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name="Department Assistant", on_delete=models.CASCADE)
added = models.DateTimeField(auto_now_add=True)
# how to query assistants from departments
# you will get objects of User model
qs = department.assistants.all()
# how to query departments from assistants
# you will get objects of Department model
qs = user.departments.all()
# If you want to query the Assistant model
# from department object
qs = department.assistant_set.all()
# from assistant object
qs = user.assistant_set.all()
# in either case you will get the objects of Assistant model
for i in qs:
print(i.added, i.department, i.assistant)
</code></pre>
<p>试试这个,如果你仍然得到错误,请告诉我</p>
<p>我的建议是将助手模型上的<code>assistant</code>字段命名为<code>user</code>。这样,您就不需要在多对多字段上定义<code>through_field</code></p>