in Education by
So in my project, I have a model Chat with many Messages. I want to have ChatSerializer with MessageSerializer inside and many=True. However, I only want to include the last 50 Message models. class MessageSerializer(serializers.ModelSerializer): class Meta(object): model = Message fields = '__all__' class ChatSerializer(serializers.ModelSerializer): messages = MessageSerializer(many=True) class Meta: model = Chat fields = '__all__' Is there anything I can add to the messages = MessageSerializer(many=True) to make it only return the latest 50 messages? Thanks! JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)

1 Answer

0 votes
by
You can use a SerializerMethodField within ChatSerializer as follows: messages = serializers.SerializerMethodField() def get_messages(self, chat): qs = Message.objects.filter(chat=chat).order_by('-date')[:50] return MessageSerializer(instance=qs, many=True).data This runs a separate query for every Chat instance, but it only fetches the required number of rows. You'd have to customize the field names (chat, date) as applicable. The alternative syntax @spiritsree is aiming at results in the same SQL, using implicit rather than explicit filtering: qs = chat.messages.order_by('-date')[:50] One thing to avoid is using prefetch_related('messages') in the queryset of the ViewSet that returns the Chat list as that prefetch won't be used at all and would haul in all messages from the database only to be discarded unused. The subquery alternative dismissed in another answer as slow is in fact quite interesting. It saves you as many roundtrips to the database as there are Chats. In exchange however, the database has to execute twice as many queries internally. The excess queries being quite lightweight (selecting a small number of messages by id and ordering them), the saved roundtrips may easily make up for them. In my quick tests this method was more than 10x as fast as using SerializerMethodField. It may depend to some extent on the data; test it for yourself: from rest_framework import viewsets from django.db.models import Prefetch, Subquery, OuterRef class ChatViewSet(viewsets.ModelViewSet): prefetch = Prefetch( 'messages', queryset=Message.objects .filter(id__in=Subquery(Message.objects .filter(chat=OuterRef('chat_id')) .order_by('-date') .values_list('id', flat=True)[:4])) .order_by('-date') ) queryset = Chat.objects.prefetch_related(prefetch)

Related questions

0 votes
    I have the following models: class Project(models.Model): name = models.CharField(max_length=300, unique= ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked May 22, 2022 in Education by JackTerrance
0 votes
    I have a very long forms.py and I'd like to split it to smaller parts with as few as possible ... , JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Mar 4, 2022 in Education by JackTerrance
0 votes
    I have a situation where i have a list of primary keys. And i need to filter(OR) a queryset ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 19, 2022 in Education by JackTerrance
0 votes
    I have a situation where i have a list of primary keys. And i need to filter(OR) a queryset ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 19, 2022 in Education by JackTerrance
0 votes
    I have a situation where i have a list of primary keys. And i need to filter(OR) a queryset ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 19, 2022 in Education by JackTerrance
0 votes
    Issue Recently I came across an issue with a client, that has many solutions, but none was easy. ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked May 17, 2022 in Education by JackTerrance
0 votes
    I need to create JWT token authentication, but I don't know how, could you explain me how to do ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Apr 17, 2022 in Education by JackTerrance
0 votes
    I have a model with two foreign keys to create many to many relationship - I am not using many to ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 27, 2022 in Education by JackTerrance
0 votes
    I have a model with two foreign keys to create many to many relationship - I am not using many to ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 26, 2022 in Education by JackTerrance
0 votes
    How to get a particular item in the Model in Django?...
asked Jul 2, 2021 in Technology by JackTerrance
0 votes
    How to filter items in the Model in Django?...
asked Jul 1, 2021 in Technology by JackTerrance
0 votes
    What is the difference between DELETE and TRUNCATE statements?...
asked Dec 11, 2020 by JackTerrance
0 votes
    What is the difference between DROP and TRUNCATE statements?...
asked Dec 9, 2020 in Technology by JackTerrance
0 votes
    What are the TRUNCATE, DELETE and DROP statements?...
asked Dec 9, 2020 in Technology by JackTerrance
0 votes
    Suggestions needed for creating better and efficient search indexes for models having foreign key and many-to-many ... for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Mar 4, 2022 in Education by JackTerrance
...