我是django初学者,所以代码可能是基本的或错误的,但无论如何...... 我有以下型号:
from django.db import models
from django.conf import settings
GRADE_CHOICES = (
('1', '1'),
('2', '2'),
('3', '3'),
('4', '4'),
('5', '5'),
('6', '6'),
('7', '7'),
('8', '8'),
('9', '9'),
('10', '10'),
)
class Professor(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=30)
def __str__(self):
rta = self.first_name+" "+self.last_name
return rta
class Student(models.Model):
first_name = models.CharField(max_length=20, blank=False, null=False)
last_name = models.CharField(max_length=30, blank=False, null=False)
def __str__(self):
rta = self.first_name+" "+self.last_name
return rta
class Subject(models.Model):
first_name = models.CharField(max_length=50)
students = models.ManyToManyField(Student, blank=True)
professors = models.ManyToManyField(Professor, blank=True)
def __str__(self):
return self.first_name
class Grade(models.Model):
value = models.CharField(choices=GRADE_CHOICES, max_length= 2)
subject = models.ForeignKey(Grade, on_delete=models.CASCADE, related_name='fk_grade')
student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='fk_student')
def __str__(self):
return self.value
要添加成绩,我需要选择主题和学生,所以我想根据他们所属的主题过滤学生。 如果学生不在该科目中,则不应出现在列表中。
我正在使用django 1.11和python 2.7。
答案 0 :(得分:0)
您的对象Subject
不应与Student
和Subject
相关联,而应与Student
和class Professor(models.Model):
# ...
class Student(models.Model):
# ...
professors = models.ManyToManyField(Person, through='Subject')
class Subject(models.Model):
name = models.CharField(max_length=50)
student = models.ForeignKey(Student, on_delete=models.CASCADE)
professor = models.ForeignKey(Professor, on_delete=models.CASCADE)
value = models.CharField(choices=GRADE_CHOICES, max_length= 2)
之间的关系相关联。有些人喜欢:
[
{ "$group": {
"_id": {
"year": { "$year": "$date" },
"type": "$type",
"color": "$color"
},
"count": { "$sum": "$soldFor" }
} },
{ "$group": {
"_id": {
"year": "$_id.year",
"type": "$_id.type"
},
"counts": {
"$push": {
"k": "$_id.color",
"v": { "sum": "$count" }
}
}
} },
{ "$addFields": {
"counts": { "$arrayToObject": "$counts" }
} },
{ "$group": {
"_id": "$_id.year",
"counts": {
"$push": {
"k": "$_id.type",
"v": "$counts"
}
}
} },
{ "$addFields": {
"counts": { "$arrayToObject": "$counts" }
} },
{ "$group": {
"_id": null,
"counts": {
"$push": {
"k": { "$substr": ["$_id", 0, -1 ]},
"v": "$counts"
}
}
} },
{ "$replaceRoot": {
"newRoot": {
"$mergeObjects": [
{ "$arrayToObject": "$counts" },
"$$ROOT"
]
}
} },
{ "$project": { "counts": 0 } }
]