Django-rest序列化器返回代码而不是对象列表

时间:2016-05-04 17:20:44

标签: python django django-rest-framework

我的Django-rest应用程序中有一个端点,我期望收到以下get响应:

{
    "my_objects": [
    {
      "my_object_order": 1,
      "related_topics": [{"title": "my_title", "subtitle": "my_subtitle"}, {"title": "my_title2", "subtitle": "my_subtitle2"}],
      "collected_at": "2016-05-02T20:52:38.989Z",
    }]
}

为了达到这个目的,您可以在下面观察我的 serializers.py

class TopicSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyTopic
        fields = ["title", "subtitle"]

class MyObjectSerializer(serializers.ModelSerializer):

    related_topics = TopicSerializer(many=True)

    class Meta:
        model = MyObject
        fields = ("my_object_order",
                  "related_topics")

    def create(self, validated_data):
        """
        Saving serialized data
        """
        related_topics_list = validated_data.pop("related_topics", [])
        obj = MyObject.objects.create(**validated_data)
        for topics_data in related_topics_list:
            MyTopic.objects.create(trend=trend, **topics_data)
        return obj

根据建议,您可以在此处查看我的 models.py

class MyObject(models.Model):
    my_object_order = models.IntegerField()
    collected_at = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.story_title


class MyTopic(models.Model):
    my_obj = models.ForeignKey(MyObject, related_name="related_topics")
    title = models.CharField(max_length=50, blank=False, null=True)
    subtitle = models.CharField(max_length=50, blank=True, null=True)

    def __unicode__(self):
        return self.title

以下是 views.py

的摘录
def get(self, request):
    params = request.QUERY_PARAMS
    # Filtering data
    obj_list = my_fun(MyObject, params)
    response = {"my_objects": obj_list.values("my_object_order",
                                             "collected_at",
                                             "related_topics")}
    return Response(response)

我查看了文档,但是我很困惑/不能从根本上理解我应该做什么。

1 个答案:

答案 0 :(得分:1)

您的问题出在views.py中,您实际上根本没有使用序列化程序。您只是过滤一些数据并返回从数据库获得的任何值(因此仅限ID)。

我建议您查看Generic Class Based Views

from myapp.models import MyObject
from myapp.serializers import MyObjectSerializer
from rest_framework import generics

class MyObjectListAPIView(generics.ListAPIView):
    queryset = MyObject.objects.all()
    serializer_class = MyObjectSerializer

此外,如果您需要任何过滤检查文档here。基本上,您可以使用此代码段

按模型中的字段进行过滤
filter_backends = (filters.DjangoFilterBackend,)
filter_fields = ('field1', 'field2')

PS:您可以将视图作为普通函数执行,但是您必须自己处理过滤/序列化部分,代码可能看起来不像基于类的视图那么清晰。