筛选QuerySet以提供数据表的最有效方法是什么?

时间:2015-07-24 07:12:16

标签: python django datatables

为了使用django_datatables_view来过滤s3=AmazonS3Client(new PropertiesCredentials("path of your s3 credential file")); datatables,我尝试覆盖方法QuerySet,但不能get_initial_queryset或提出一个清晰的itertools.chain对象表达式来完成这项工作。

Q

因此,要获取每个class Student(models.Model): identity = models.CharField(max_length=50, unique=True) name = models.TextField() age = models.IntegerField() class Status(models.Model): student = models.ForeignKey('Student') status = models.TextField() time = models.DateTimeField() 的最新Status并实际将它们合并/合并为一个Student对象,以使其在QuerySet中有效,应该是什么我呢?

2 个答案:

答案 0 :(得分:0)

我所理解的是你需要覆盖这两个功能:

def get_initial_queryset(self):
    return Status.objects.select_related('student')

def prepare_results(self, qs):
    json_data = []
    for item in qs:
        json_data.append([item.student, item.status])
    return json_data

有关详细信息read the docs here.

答案 1 :(得分:0)

嗯,我不确定这是否效率最高,但你可以这样做(这是未经测试的):

students = Student.objects.all()
status_ids = []

for student in students:
    latest_status_id = Status.objects.filter(student=student) \
                                     .latest('time').id
    status_ids.append(latest_status_id)

latest_statuses = Status.objects.filter(pk__in=statues)