【发布时间】:2017-11-02 10:18:49
【问题描述】:
我的模型定义如下:
class Subject(models.Model):
subject_id = models.IntegerField(primary_key=True)
subject_name = models.CharField(max_length=20)
class Teacher(models.Model):
teacher_id = models.CharField(max_length=10, primary_key=True)
teacher_name = models.CharField(max_length=30)
teacher_age = models.IntegerField()
teacher_doj = models.DateField()
subjects = models.ManyToManyField(Subject)
class TeacherScores(models.Model):
co_id = models.CharField(primary_key = True, max_length=5)
internal_score = models.IntegerField()
external_score = models.IntegerField()
teacher = models.ManyToManyField(Teacher)
下面显示了几个数据库条目
老师
+------------+--------------+-------------+-------------+
| teacher_id | teacher_name | teacher_age | teacher_doj |
+------------+--------------+-------------+-------------+
| AC23001 | Tina | 32 | 2017-04-10 |
| AC23002 | Rina | 31 | 2009-04-10 |
| AC23003 | Tom | 35 | 2009-04-10 |
| AC23004 | Henry | 56 | 2009-04-10 |
+------------+--------------+-------------+-------------+
主题
+------------+--------------+
| subject_id | subject_name |
+------------+--------------+
| 1 | English |
| 2 | Hindi |
| 3 | Sanskrit |
| 4 | Math |
| 5 | Physics |
| 6 | Chemistry |
| 7 | Biology |
| 8 | History |
| 9 | Civics |
| 10 | Geography |
| 11 | MoralScience |
| 12 | Algebra |
+------------+--------------+
teacher_subject
+----+------------+------------+
| id | teacher_id | subject_id |
+----+------------+------------+
| 4 | AC23002 | 4 |
| 5 | AC23002 | 8 |
| 2 | AC23002 | 12 |
| 6 | AC23003 | 5 |
| 7 | AC23003 | 9 |
| 10 | AC23004 | 5 |
| 8 | AC23005 | 9 |
| 9 | AC23005 | 10 |
| 11 | AC23006 | 12 |
| 12 | AC23007 | 6 |
| 13 | AC23008 | 6 |
+----+------------+------------+
基本上,我想为他/她处理的每个科目的特定教师添加条目到 TeacherSCores 模型中。 在这里,我想修改 TeacherScores 模型,以便我可以包含每个科目的教师分数。 我尝试通过 Teacherscores 对象插入主题,但出现错误。
>>> t1 = TeacherScores('C006','23','24',teacher__subject='Math')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/base.py", line 572, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'teacher__subject' is an invalid keyword argument for this function
>>> t1 = TeacherScores('C006','23','24',teacher__subjects='Math')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/base.py", line 572, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'teacher__subjects' is an invalid keyword argument for this function
如何更改我的模型 - TeacherScores 以包含教师的 学科字段,前提是在教师和学科之间定义了 ManyToMany 字段,以及 TeacherScores 和 Teacher
【问题讨论】:
标签: django django-models many-to-many