我有一个具有以下定义的模型
class exam_questions(models.Model):
exam_name=models.ForeignKey(exam,on_delete=models.CASCADE)
question=models.ForeignKey(questions,on_delete=models.CASCADE)
class Meta:
db_table = 'examquestions'
unique_together = (("exam_name", "question"),)
def __str__(self):
return '%s - %s' % (self.exam_name, self.question)
sql表上的数据将如下所示
+----+----------------+-------------+
| id | exam_name | question |
+----+----------------+-------------+
| 2 | test2 | 29 |
| 3 | test1 | 41 |
| 6 | test2 | 40 |
| 7 | test1 | 42 |
+----+----------------+-------------+
在Django admin上,我正在寻找如下模型对象:
test2-29
test1-41
test2-40
test1-42
现在我想对同一测试的问题进行分组,并希望看起来像下面这样:
test2-29,40
test1-41,42
我尝试使用普通的python字符串操作,没有一个在amdin django上工作而是给了我错误。
有没有办法做到这一点。非常感谢任何帮助。
谢谢
答案 0 :(得分:0)
You can override objects manager in this way :-
class ExamManager(models.Manager):
def get_queryset(self):
return super(ExamManager,self).get_queryset().group_by('exam_name')
class exam_questions(models.Model):
exam_name=models.ForeignKey(exam,on_delete=models.CASCADE)
question=models.ForeignKey(questions,on_delete=models.CASCADE)
objects = ExamManager()