Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/vim/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django rest framework Django rest框架序列化了许多模型的queryset_Django Rest Framework_Django Queryset - Fatal编程技术网

Django rest framework Django rest框架序列化了许多模型的queryset

Django rest framework Django rest框架序列化了许多模型的queryset,django-rest-framework,django-queryset,Django Rest Framework,Django Queryset,我想合并来自2个不同模型的2个查询集,然后我需要按日期排序,最后我的目标是序列化它 到目前为止,我做到了: last_actions = serializers.SerializerMethodField() def get_last_actions(self, obj): prc = obj.product_request_configs.all().order_by('modified_date')[:5] psc = obj.product_send_configs.a

我想合并来自2个不同模型的2个查询集,然后我需要按日期排序,最后我的目标是序列化它

到目前为止,我做到了:

last_actions = serializers.SerializerMethodField()

def get_last_actions(self, obj):

    prc = obj.product_request_configs.all().order_by('modified_date')[:5]
    psc = obj.product_send_configs.all().order_by('modified_date')[:5]

    result_list = sorted(
        chain(prc, psc),
           key=attrgetter('modified_date'),
           reverse=True)
但我不知道如何调用我的两个django rest序列化程序,以便返回正确的数据


如果我可以创建一个数据库视图,我想它会更简单。

序列化程序是为匹配一个模型关系而设计的,因此我们需要为您试图实现的逻辑创建一个自定义的
模型:

class CustomModel(models.Model):

    def dictfetchall(self, cursor):
        """Returns all rows from a cursor as a dict"""
        desc = cursor.description
        return [dict(zip([col[0] for col in desc], row))
                for row in cursor.fetchall()]

    def yourMethod(self):
        cursor = connection.cursor()
        cursor.execute("""
                        select field1, field2 from app_table
                        where field1=%s and field2=%s group by field1
                        """,
                        [value1, value2,]
                      )
        return self.dictfetchall(cursor)

    class Meta:
        abstract = True
这将返回一个字典,然后您可以使用seializer序列化该响应,如:

class CustomModelSerializer(serializers.Serializer):
    field1 = serializers.IntegerField()
    field2 = serializers.CharField()
请注意,在SQL上,您可以使用
作为
关键字重命名某些字段,字段的当前名称必须与序列化程序中的变量名称匹配