【问题标题】:JOIN Two table in DJANGO with aggregate用聚合连接 DJANGO 中的两个表
【发布时间】:2019-02-13 02:36:30
【问题描述】:

我已经在 django 上玩了一个月了,但我一直坚持使用 Aggregate 加入两个表。这是我的models.py

class Student(models.Model):
    student_number_format = RegexValidator(regex=r"^20{1,2}[1-2][0-9]-[0-9]{6}", message="Please enter a valid student number (example:2019-123456)")
    student_number  = models.CharField(validators=[student_number_format], max_length=11, blank=True, unique=True, help_text="Student number must be this format 20YY-99999")
    student_course  = models.ForeignKey(Course, on_delete=models.CASCADE)
    first_name      = models.CharField(max_length=255)
    middle_initial  = models.CharField(max_length=2)
    last_name       = models.CharField(max_length=255)
    profile_picture = models.ImageField(upload_to=user_directory_path)
    date_registered = models.DateTimeField(default=timezone.now)

class DataSets(models.Model):
    student_info  = models.ForeignKey(Student, on_delete=models.CASCADE)
    dataset_image = models.ImageField(upload_to=dataset_directory_path)
    date_upload   = models.DateTimeField(default=timezone.now)

在这里我有两个模型,DataSets 类有一个外键给学生。我只想显示在 DataSets 中有 5 个或更多数据的学生。这是 SQL 表示:

SELECT Count(student_info) as Count, A.first_name as Name 
FROM Student A
JOIN DataSets B ON A.id = B.student_info_id
WHERE Count >= 5

【问题讨论】:

    标签: django django-models aggregate


    【解决方案1】:

    您可以使用 select_relatedlink 执行此操作。我希望以下查询能够工作。

    DataSets.objects.select_related('student_info').annotate(
         entries=models.count()).filter(entries__gte=5)
    

    【讨论】:

    • 好吧,我试过你的代码,但我只返回一个空的查询集。谢谢你
    • @CarlDennisAlingalan 而不是 student_info_id 你可以试试student_info
    • 是的,我在 models.py 中创建了一个函数,那么我的下一个问题是,当我在函数中使用“self”参数时,它实际上要求我给它一个参数。这是我的代码
    • ` def valid_student(self):valid = self.values('student_info').annotate(entries=models.Count('student_info')).filter(entries__gte=5) student = [Student .objects.get(id=stud_num['student_info']) for stud_num in valid] 返回学生`
    • 这是我的使用方法 liststud = DataSets.valid_student(DataSets.objects)
    猜你喜欢
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2022-01-24
    相关资源
    最近更新 更多