Return results from multiple models with Django REST Framework

2024/11/18 19:59:16

I have three models — articles, authors and tweets. I'm ultimately needing to use Django REST Framework to construct a feed that aggregates all the objects using the Article and Tweet models into one reverse chronological feed.

Any idea how I'd do that? I get the feeling I need to create a new serializer, but I'm really not sure.

Thanks!

Edit: Here's what I've done thus far.

app/serializers.py:

class TimelineSerializer(serializers.Serializer):pk = serializers.Field()title = serializers.CharField()author = serializers.RelatedField()pub_date = serializers.DateTimeField()

app/views.py:

class TimelineViewSet(viewsets.ModelViewSet):"""API endpoint that lists all tweet/article objects in rev-chrono."""queryset = itertools.chain(Tweet.objects.all(), Article.objects.all())serializer_class = TimelineSerializer
Answer

It looks pretty close to me. I haven't used ViewSets in DRF personally, but I think if you change your code to this you should get somewhere (sorry - not tested either of these):

class TimelineViewSet(viewsets.ModelViewSet):"""API endpoint that lists all tweet/article objects in rev-chrono."""def list(self, request):queryset = list(itertools.chain(Tweet.objects.all(), Article.objects.all()))serializer = TimelineSerializer(queryset, many=True)return Response(serializer.data)

If you're not wedded to using a ViewSet then a generics.ListAPIView would be a little simpler:

class TimeLineList(generics.ListAPIView):serializer_class = TimeLineSerializerdef get_queryset(self):return list(itertools.chain(Tweet.objects.all(), Article.objects.all()))

Note you have to convert the output of chain to a list for this to work.

https://en.xdnf.cn/q/26524.html

Related Q&A

Comparing XML in a unit test in Python

I have an object that can build itself from an XML string, and write itself out to an XML string. Id like to write a unit test to test round tripping through XML, but Im having trouble comparing the tw…

Passing a tuple as command line argument

My requirement is to pass a tuple as command line argument like --data (1,2,3,4)I tried to use the argparse module, but if I pass like this it is receiving as the string (1,2,3,4). I tried by giving ty…

Setting exit code in Python when an exception is raised

$ cat e.py raise Exception $ python e.py Traceback (most recent call last):File "e.py", line 1, in <module>raise Exception Exception $ echo $? 1I would like to change this exit code fr…

cmake error the source does not appear to contain CMakeLists.txt

Im installing opencv in ubuntu 16.04. After installing the necessary prerequisites I used the following command:-kvs@Hunter:~/opencv_contrib$ mkdir build kvs@Hunter:~/opencv_contrib$ cd build kvs@Hunte…

Overlay an image segmentation with numpy and matplotlib

I am trying to overlay two images. The first one is a 512x512 NumPy array (from a CT image). The second one is also a 512x512 NumPy array but I am just interested in the pixels where the value is large…

Why isnt my variable set when I call the other function? [duplicate]

This question already has answers here:How do I get ("return") a result (output) from a function? How can I use the result later?(4 answers)How can I fix a TypeError that says an operator (…

Return max of zero or value for a pandas DataFrame column

I want to replace negative values in a pandas DataFrame column with zero.Is there a more concise way to construct this expression?df[value][df[value] < 0] = 0

Getting str object has no attribute get in Django

views.pydef generate_xml(request, number):caller_id = x-x-x-xresp = twilio.twiml.Response()with resp.dial(callerId=caller_id) as r:if number and re.search([\d\(\)\- \+]+$, number):r.number(number)else:…

Cython Speed Boost vs. Usability [closed]

Closed. This question is opinion-based. It is not currently accepting answers.Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.Clo…

cc1plus: warning: command line option -Wstrict-prototypes is valid for Ada/C/ObjC but not for C++

I am building a C++ extension for use in Python. I am seeing this warning being generated during the compilation process - when a type:python setup.py build_ext -iWhat is causing it, and how do I fix i…