我有一个名为Course的模型,我一直在尝试使用过滤器功能获取它们的列表。现在每个课程都有不同的领域。
我的课程模型是:
class Course(models.Model):
course_code = models.CharField(max_length=20)
course_university = models.CharField(max_length=100)
course_instructor = models.CharField(max_length=100)
course_year = models.IntegerField(('year'), validators=[MinValueValidator(1984), MaxValueValidator(max_value_current_year())])
course_likes = models.ManyToManyField(Profile, blank=True, related_name='course_likes')
course_dislikes = models.ManyToManyField(Profile, blank=True, related_name='course_dislikes')
course_reviews = models.ManyToManyField(Review, blank=True, related_name='course_reviews')
我正尝试在牛津大学获得名为“史密斯”的讲师课程
courses = Course.objects.filter(course_instructor="smiths",course_university="university")
How can I remove duplicated with this name for instance show the one with the latest year?
Sine, for example, there will be course ABC123 by professor Smith in Oxford university in years 2017,2018,2019,... how can I return only one of those? I have tried distinct()
but it doesn't work.
有什么办法吗?还是应该更改数据库的整体结构?
编辑:我尝试了此,但它仍然给我重复:
course_dup = Course.objects.filter(course_instructor=par2,course_university=par1).values('course_instructor', 'course_university').annotate(course_year=Max('course_year'))
courses = Course.objects.filter(course_instructor__in=[c['course_instructor'] for c in course_dup], course_university__in=[c['course_university'] for c in course_dup])
因此,为澄清起见,假设有以下值:
course_code | course_instructor | course_year | course_university
1. ABC123 | smith | 2017 | Oxford
2. ABC123 | smith | 2017 | Oxford
3. CDE123 | smith | 2018 | Oxford
4. ADF123 | smith | 2019 | Oxford
5. ABC123 | smith | 2019 | Oxford
我只想返回例如3,4,5,因为5是最新的课程代码ABC123,甚至返回1,3,4的查询也应该工作,因为1是与查询匹配的第一个匹配项。我该如何实现?
这样可以解决你的问题
这将排除第一个值并删除其余的值