在DJANGO中将两个表合并在一起

时间:2019-02-13 02:36:30

标签: django django-models aggregate

我已经和django玩了一个月了,而我一直在坚持用Aggregate联接两个表。这是我的模型。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类具有学生的外键。我只想显示在DataSet中具有5个或更多数据的Student。这是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

1 个答案:

答案 0 :(得分:0)

您可以使用select_related link进行此操作。我希望以下查询能够正常工作。

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