0

I have an endpoint in my Django-rest application in which I expect to receive the following get response:

{
    "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",
    }]
}

In order to achieve that, below you can observe my 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

As suggested, here you can see my 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

Below you have the excerpt from my 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)

I have looked on the documentation, however I am confused/not understanding fundamentally what I should do.

8
  • Please add the models and the implementation of my_fun as well. Commented May 4, 2016 at 17:22
  • You are missing a "]" bracket in your first and last code block Commented May 4, 2016 at 17:22
  • Implementation of my_fun is not relevant. If it was, you would have access to it already. Models are relevant indeed, I will add in a bit. Commented May 4, 2016 at 17:28
  • @AaronLelevier, this comment is more related to my response data, which has nothing to do with my real problem reported here. But I can fix that, thank you for pointing it out. Commented May 4, 2016 at 17:29
  • @RicardoSilveira take a look on this: django-rest-framework.org/api-guide/serializers/… Commented May 4, 2016 at 18:39

1 Answer 1

1

Your problem is in views.py, you are not using actually the serializer at all. You are just filter some data and return whatever values you get from database (hence the ids only).

I suggest you to check 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

Also if you need any filtering check documentation here. Basically you can filter by fields from model with this snippet

filter_backends = (filters.DjangoFilterBackend,)
filter_fields = ('field1', 'field2')

PS: You can do the view as normal function, but you have to handle yourself filtering/serialization part, the code may not look as cleaner as you get with class based views.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.