Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add chat functionality to a django web app
I have a django app for university alumni where they can make accounts. I want to incorporate chat functionality in it so the registered users can chat with each other just like facebook. Any ideas how I can do this. Should I learn django channels or use some third-party library? I guess twilio/tawk to is an option But I don't know much. -
Unable to install Faker with command pip install Faker
The problem I have is that i am unable to install Faker in my virtual environment with pip. I've checked pip works for other packages but is unable to install Faker (MyEnv) C:\Users\cipher\PycharmProjects\udemydjango1\first_project>pip install Faker python version:3.8.1 pip version:20.2.1 django version:3.1 Whenever I go to terminal and and type pip install Faker I receive this:: Unable to create process using 'C:\Users\cipher\anaconda3\envs\MyEnv\python.exe C:\Users\cipher\anac onda3\envs\MyEnv\Scripts\pip-script.py install Faker' What's wrong here?Please help! -
python django search image by dominant color
I'm bulidng a website with bunch of pictures in it using django(3.0) python(3.8). I'm trying to make a filter where a user select a color and give back images of which dominant color is the color user requested. To do that, use colorgram (pip install colorgram.py) to extract two dominant colors(except those too white) and save it to 'dominant_color' field when saving instance. def RgbToInt(rgb): red = rgb[0] green = rgb[1] blue = rgb[2] RGBint = (red << 16) + (green << 8) + blue return RGBint class Design(models.Model): ...fields... image = ImageField(upload_to=upload_image_path) dominant_color = models.CharField(max_length=80, blank=True) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): img = Image.open(self.image.path).resize((180, 180)) colors = colorgram.extract(img, 3) white = 210 color = [f'{RgbToInt(c.rgb)},{int(round(c.proportion * 100, 0))}' for c in colors if not (c.rgb[0] > white and c.rgb[1] > white and c.rgb[2] > white)] if len(color) > 3: color = color[:2] self.dominant_color = color super(Design, self).save(force_insert=False, force_update=False, using=None, update_fields=None) -- Colorgram gives result like below: [<colorgram.py Color: Rgb(r=252, g=251, b=249), 72.43592003666748%>, <colorgram.py Color: Rgb(r=196, g=170, b=103), 18.46067059196841%>, <colorgram.py Color: Rgb(r=194, g=150, b=37), 9.103409371364101%>] -- I save it as string in Design model as below: ['12888679,18', '12752421,9'] get color query argument from request and do comparison within view. … -
How to Update ImageField in Django?
i am new in Django. i am having issue in updating ImageField.i have following code in models.py class ImageModel(models.Model): image_name = models.CharField(max_length=50) image_color = models.CharField(max_length=50) image_document = models.ImageField(upload_to='product/') -This is My forms.py class ImageForm(forms.ModelForm): class Meta: model = ImageModel fields = ['image_name', 'image_color' , 'image_document'] in Html file (editproduct.html) <form method="POST" action="/myapp/updateimage/{{ singleimagedata.id }}"> {% csrf_token %} <input class="form-control" type="text" name="image_name" value="{{ singleimagedata.image_name}}"> <input class="form-control" type="file" name="image_document"> <button type="submit" class="btn btn-primary">UPDATE PRODUCT</button> </form> -myapp is my application name. {{singleimagedata}} is a Variable Containing all fetched Data -urls.py urlpatterns = [ path('productlist', views.productlist, name='productlist'), path('addproduct', views.addproduct, name='addproduct'), path('editimage/<int:id>', views.editimage, name='editimage'), path('updateimage/<int:id>', views.updateimage, name='updateimage'), ] and Here is My views.py def productlist(request): if request.method == 'GET': imagedata = ImageModel.objects.all() return render(request,"product/productlist.html",{'imagedata':imagedata}) def addproduct(request): if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Image Uploaded') return redirect('/myapp/productlist') else: imageform = ImageForm() return render(request, "product/addproduct.html", {'imageform': imageform}) def editimage(request, id): singleimagedata = ImageModel.objects.get(id=id) return render(request, 'product/editproduct.html', {'singleimagedata': singleimagedata}) def updateimage(request, id): #this function is called when update data data = ImageModel.objects.get(id=id) form = ImageForm(request.POST,request.FILES,instance = data) if form.is_valid(): form.save() return redirect("/myapp/productlist") else: return render(request, 'demo/editproduct.html', {'singleimagedata': data}) My image Upload is working fine.i can not Update image while updating data.rest … -
Difference in password validators and regular validators in Django
I am having problems understanding why there is a difference in the structure of password validators vs regular validators in Django. Following the docs each validator should be a callable (beeing a class or function) that raises an ValidationError should the input not validate, else None. In the linked docs also provide an overview over the implemented validators. However I find there are validators that are not listed there - namely password validators. These ca be found in the django.contrib.auth.password_validation module. Also these validators seem to follow a different philosophie in their structure. Instead of the behaviour described above, the validators seem to be classes with a method called validate. Here is a tutorial I found that explains the creation of such validators. Now my question is, why and how is there a difference in these validators? Why are the password validators not listed in the docs for validators and why were they created differently? Am I missing something? Could someone please give me some insight into the in and outs of this concept? Isnt it misleading to have a list of validators and then not include the password validators in it? Thanks in advance! -
Python Django manage.py run npm commands on top of it (using django app and vue app simultaneously)
I am building a django website that has both a vanilla django app and a Vue app. Directories are somewhere in this format: - mysite - main - asgi.py - settings.py - .. - frontend (this is the vanilla django app) - .. - vueapp (this is the vue app) - .. At the moment I can go into '/mysite' and run python manage.py runserver. This will run only the stuff in the main and frontend directories to create a localhost. But one part of the website is a vue app. I can go into '/mysite/vueapp' and do npm run serve. This will run just the vue part of the website. Basically my question is how should i go about using them together? I tried running python manage.py runserver and npm run serve at the same time on 2 different terminals but they overwrite each other. I know this can be a tricky question (maybe not even explained too well) so please ask me things about the project if they are relevant to solving my issue and ill do my best to answer them. -
Django: How to populate other model fields when someone leaves a comment
I am trying to let anyone post a comment on a blog but there are other fields in my model that need to get information that is not required in the form itself. I've tried adding it in the form_valid method but that method is not being called when the form is submitted. Any help is appreciated views.py class CommentView(CreateView): template_name = "core/index.html" model = Comment form_class = CommentForm def get_success_url(self): return reverse_lazy("core:home") def form_valid(self, form): print("form is valid") form.save() return super().form_valid(form) forms.py class CommentForm(ModelForm): class Meta: model = Comment fields = [ "text", ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["text"].widget.attrs.update( {"class": "form-control", "placeholder": "Enter Your Comment Here",} ) models.py class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey( BlogPost, on_delete=models.CASCADE, related_name="comments" ) text = models.TextField(max_length=255, default="") date_posted = models.DateTimeField(auto_now_add=True) def __str__(self): return f"({self.author})'s comment on ({self.post.title})" urls.py app_name = "blog" urlpatterns = [ path("post/<int:pk>/", BlogPostDetailView.as_view(), name="detail"), path("post/category/<int:pk>/", CategoryListView.as_view(), name="category"), path("post/comment/<int:pk>/", CommentView.as_view(), name="comment"), ] -
How to add a method to every admin.ModelAdmins?
I try to get 2 links in the admin change list view (change and view) based on Django permissions ('can change' and 'can edit') on every model I have. I want to have a generic way and don't want to copy the code in all of my ModelAdmins. How can I do that? class MyModelAdmin(admin.ModelAdmin): list_display = ('admin_action_column', 'name') # get user to changelist view (permission checks) def changelist_view(self, request, *args, **kwargs): self.user = request.user return super().changelist_view(request, *args, **kwargs) def admin_action_column(self, obj): admin_link_s = "" app_label = self.model._meta.app_label model_name = self.model._meta.model_name if self.user.has_perm(f'{app_label}.view_{model_name}'): admin_link_s += obj.admin_get_view_link() if self.user.has_perm(f'{app_label}.change_{model_name}'): admin_link_s += obj.admin_get_change_link() return mark_safe(admin_link_s) admin_action_column.short_description = '' admin.site.register(MyModel, MyModelAdmin) -
JSONDecodeError at /signUp Expecting value: line 1 column 1 (char 0)
I am implementing membership using JSON module.First of all, I used json.loads to get the value that came into body, and then I wrote a code to put it in the user model. However, the following error occurs here. JSONDecodeError at /signUp Expecting value: line 1 column 1 (char 0) I wonder what's wrong with my code, and I want to know the solution to it. Here is my code. thank in advance views.py from django.core.mail import EmailMessage from rest_framework.views import APIView from rest_framework.generics import CreateAPIView from rest_framework.permissions import IsAuthenticated from .serializers import userDetailSerializer, emailSerializer, userSerializer from .models import User, userDetail, email import random import string import json class userView (APIView) : serializer_class = userSerializer def post(self, request) : data = json.loads(request.body) if User.objects.filter(email = data['email']).exists() : return JsonResponse({"message" : "이미 존재하는 아이디입니다."}, status = 401) else: User.objects.create(email = data['email'], password = data['password']) return redirect('emailView') class userDetailView (CreateAPIView) : serializer_class = userDetailSerializer permission_classes = [IsAuthenticated,] def get_queryset (self) : user = self.request.user queryset = userDetail.objects.filter(userId=user) return queryset class emailView (CreateAPIView) : serializer_class = emailSerializer def get_queryset (self) : user = self.request.user queryset = userDetail.objects.all() return queryset def makeNumber (self) : stirng_pool = string.digits result = '' for i in range(6) … -
Pass data from front end to a model object in django
I have an Order model, that has a remark field. I'm rendering my Order model in an HTML file and currently, I have 2 orders in my order model that are displaying in the HTML file. And both orders in the HTML file have a text field where I can manually enter a text for a particular order and pass the value into the remark field in Order model. However, when I enter a text in a text field of a specific order in my HTML file and pass the data to the Order model it creates a new object. I want to pass the data into an order object that is displaying in an HTML file. models.py class Order(models.Model): item = models.ManyToManyField('Item') name = models.CharField(max_length=30) address = models.CharField(max_length=100) remark = models.CharField(max_length = 100, null=True) views.py def order_list(request): if request.method=="POST": if request.POST.get('remarks'): saveresults=Order() saveresults.remark=request.POST.get('remarks') saveresults.save() order = Order.objects.all() context = { 'order':order, } return render(request, "order_list.html", context) HTML <table class="table table-responsive"> <thead class="bg-secondary"> <tr> <th scope="col">Item</th> <th scope="col">Name</th> <th scope="col">Address</th> </tr> </thead> <tbody> {% for order in order %} <tr> <td>{{order.item}}</td> <td>{{ Order.name }}</td> <td>{{ Order.address }}</td> <td> <form method="POST"> <input type="text" id="txtusers" readonly name="remarks" /></td> <input type="submit" value="Inser Records..."/> … -
Hyperlinked model serializer does not work for custom routers
I have my router defined for view set as router.register('clinics/(?P<clinic_id>.+)/patients', views.PatientViewSet) I have my serializer defined class PatientSerializer(serializers.HyperlinkedModelSerializer): """Serializer for model patient """ url = serializers.HyperlinkedIdentityField(view_name="patient-detail") first_name = serializers.ReadOnlyField(source='user.first_name') last_name = serializers.ReadOnlyField(source='user.last_name') email = serializers.ReadOnlyField(source="user.email") class Meta: model = Patient fields = ["first_name", "last_name", "email", "URL"] While accessing http://localhost:8000/api/clinics/1/patients DRF gives Could not resolve URL for hyperlinked relationship using view name "patient-detail". You may have failed to include the related model in your API, or incorrectly configured the ` lookup_field` attribute on this field. This works as expected if I change URL to router.register('patients', views.PatientViewSet) -
Include template by variable
I have a model like this: class Component(models.Model) html_name = models.CharField(max_length=100) #example value: header_1.html class MyModel(models.Model): components = models.ManyToManyField(Component ...) In my Django project I have the following structure. root ----myapp --------templates ------------myapp ----------------templates --------------------default_template_1.html ----------------components --------------------header_1.html In my template(default_template_1.html) I would like to do something like this: {% for applied_component in mymodel.components.all %} {% with '../components/'|add:applied_component as component_template %} {% include component_template %} {% endwith %} {% endfor %} That gives me an error: TemplateDoesNotExist. However if I extract that string inside component_template and just hardcode it, then the include works fine. So it seems like it's something with the fact that it's a variable. I also tried changing include to: {% include component_template|stringformat:"i" %} But that gives me: PermissionError at /app/event/1/ [Errno 13] -
Reverse Foreign Key indexing in elastic search document using django elastic search dsl
hi everyone im using django-elasticsearch-dsl to create elastic search index and i need to perform full text search on one of my model called lead and all child model of lead should also be indexed so that i can perform search on lead and its child models field for example class Lead(models.Model): id = name = priority = class ProjectMatch(models.Model): """ Project Match Model """ title = possesion date = area = lead = models.Foreignkey here i have lead as a parent model so in lead document i need to index both lead and project match so that i can perform search on both lead related and project related field on lead search endpoint ,,anyone experience in ES please let me know how to handle this -
Log not emitted in Django from custom logger
I have created a custom handler and a model to save the logs to the database. The following model LogEntry is defined in applogger in models.py: from django.db import models class LogEntry(models.Model): time = models.DateTimeField(auto_now_add=True) level = models.CharField(max_length=10) message = models.TextField() I have an application called applogger with a Log Handler handlers.py: from logging import Handler import json, datetime, random class DBHandler(Handler): """ This handler will add logs to a database model defined in settings.py If log message (pre-format) is a json string, it will try to apply the array onto the log event object """ model_name = None expiry = None def __init__(self, model="", expiry=0): super(DBHandler,self).__init__() self.model_name = model self.expiry = int(expiry) def emit(self, record): # putting a pdb trace # this is not triggered import pdb; pdb.set_trace() try: # instantiate the model try: model = self.get_model(self.model_name) except: from applogger.models import GeneralLog as model log_entry = model(level=record.levelname, message=self.format(record)) # test if msg is json and apply to log record object try: data = json.loads(record.msg) for key,value in data.items(): if hasattr(log_entry,key): try: setattr(log_entry,key,value) except: pass except: pass log_entry.save() except: pass def get_model(self, name): names = name.split('.') mod = __import__('.'.join(names[:-1]), fromlist=names[-1:]) return getattr(mod, names[-1]) I have setup the following LOGGING configuration … -
Django Add messages.error message to FormView
I need to show an error message after form submission to the user. The condition is set inside the form_valid function of FormView but it is not form specific and I do not want to change the existing form logic. This is what I have tried - def form_valid(self, form): ... if condition: messages.error(self.request, 'Please ...') return super(...) Also tried this - def form_valid(self, form): ... if condition: self.message = 'Please ...' return super(...) def get_success_url(self): if self.message: messages.add_message(self.request, messages.ERROR, self.message) return self.success_url Both of them don't work. In DeleteView this can be done by overriding delete function, how to do it for FormView? -
Django Rest Partial Update
I am working on finding the critical path for a set of tasks. For that I added a critical boolean field in the task model which is set to False by default. Once this logic is run, I want to update this field as True for critical tasks. Can someone help? Also, once marked critical, I want to update the status (Textfield) for all the critical tasks in a separate model. Here are my files: models.py: class Task_category(models.Model): job = models.ForeignKey(Job,related_name='Job',on_delete=models.CASCADE, null=True) assigner = models.ForeignKey(User,related_name='assigner', on_delete=models.PROTECT, null=True) assignee = models.ForeignKey(User,related_name='assignee', on_delete=models.PROTECT, null=True) unit = models.ForeignKey(Unit,related_name='UnitName',on_delete=models.CASCADE, null=True) equipment = models.ForeignKey(Equipment,related_name='EquipmentName',on_delete=models.CASCADE, null=True) name = models.CharField(max_length=200) share_with = models.ManyToManyField(User) category = models.CharField(max_length=200, null=True,blank=True) start_date = models.DateField() start_time = models.TimeField(null=True,blank=True) end_date = models.DateField() end_time = models.TimeField(null=True,blank=True) created_at = models.DateTimeField(auto_now_add=True,blank=True, null=True) updated_at = models.DateTimeField(auto_now=True,blank=True, null=True) status = models.ForeignKey(TaskStatus, related_name='Status',on_delete=models.CASCADE) predecessor = models.ManyToManyField("self",blank=True) critical = models.BooleanField(default=False) status = models.CharField(max_length=400,default='') def __str__(self): return(self.name) views.py: class GanffView(viewsets.ModelViewSet): http_method_names = ["get"] task_list = Task_category.objects.all() subtask_list = Subtask_category.objects.all() tasks, critical = cpmlogic(task_list) The cpmlogic returns a dictionary 'tasks' which has a 'isCritical' key that is True for critical tasks. I want to use that to update the critical field in the tasks so that it can be used later on -
Django multiple foreign key to a same table
I need to log the transaction of the item movement in a warehouse. I've 3 tables as shown in the below image. However Django response error: ERRORS: chemstore.ItemTransaction: (models.E007) Field 'outbin' has column name 'bin_code_id' that is used by another field. which is complaining of multiple uses of the same foreign key. Is my table design problem? or is it not allowed under Django? How can I achieve this under Django? thankyou DB design [Models] class BinLocation(models.Model): bin_code = models.CharField(max_length=10, unique=True) desc = models.CharField(max_length=50) def __str__(self): return f"{self.bin_code}" class Meta: indexes = [models.Index(fields=['bin_code'])] class ItemMaster(models.Model): item_code = models.CharField(max_length=20, unique=True) desc = models.CharField(max_length=50) long_desc = models.CharField(max_length=150, blank=True) helper_qty = models.DecimalField(max_digits=10, decimal_places=4) unit = models.CharField(max_length=10, blank=False) def __str__(self): return f"{self.item_code}" class Meta: verbose_name = "Item" verbose_name_plural = "Items" indexes = [models.Index(fields=['item_code'])] class ItemTransaction(models.Model): trace_code = models.CharField(max_length=20, unique=False) item_code = models.ForeignKey( ItemMaster, related_name='trans', on_delete=models.CASCADE, null=False) datetime = models.DateTimeField(auto_now=False, auto_now_add=False) qty = models.DecimalField(max_digits=10, decimal_places=4) unit = models.CharField(max_length=10, blank=False) action = models.CharField( max_length=1, choices=ACTION, blank=False, null=False) in_bin = models.ForeignKey( BinLocation, related_name='in_logs', db_column='bin_code_id', on_delete=models.CASCADE, null=False) out_bin = models.ForeignKey( BinLocation, related_name='out_logs', db_column='bin_code_id', on_delete=models.CASCADE, null=False) remarks = models.TextField(blank=True) def __str__(self): return f"{self.trace_code} {self.datetime} {self.item_code} {dict(ACTION)[self.action]} {self.qty} {self.unit} {self.in_bin} {self.out_bin}" -
Display loader while neural network model is running on backend
I am trying to run a neural network model on the backend and want to display results on the front end. I am using django. I am saving graph images into a buffer and then sending them as context to the template page. I am using the code below buf = io.BytesIO() fig.savefig(buf, format='png') buf.seek(0) string = base64.b64encode(buf.read()) uri = urllib.parse.quote(string) return render(request, 'graph/index.html', {'data': uri}) While running my neural network as it takes some time to produce results, I want to show a loader on the template page. Is there an easy way to do this ? Thanks in advance -
Multiple admins in Django is it possible
Is it possible to add multiple admins in Django's admin panel and how I will register them(they need to have the same rights)? And also is it possible to add another 2 roles to the panel with different rights? I read a lot about it and can't find the answer. I will really appreciate your help! -
How to retrieve image in mongoengine and Django rest framework
Problem: No guide on how should i retrieve image binary or image itself and serve it on frontend. I can upload image to mongodb but not being able to retrieve it's data. Model: class Images(Document): name = fields.StringField() image = ImageField() ImageField directly uploads image to mongodb and i don't know how to retrieve it Serializer: class ImageSerializer(serializers.DocumentSerializer): class Meta: model = Images fields = '__all__' View: class ImageViewSet(viewsets.ModelViewSet): serializer_class = ImageSerializer def get_queryset(self): return Images.objects.all() Please help me to send the image or image binary data to frontend. Been trying it for a while and unable to complete it. -
How can i use 1 to 20 number inside " json()[' inside this '] " [duplicate]
here is my views.py from django.shortcuts import render import requests def home(request): data = True result = None globrep = None countries = None res = None ind = None city = None city1 = None while (data): try: result = requests.get("https://api.covid19api.com/summary") globrep = result.json()['Global'] countries = result.json()['Countries'] res = requests.get("https://api.covid19india.org/data.json") ind = res.json()['statewise'] city = requests.get("https://api.covidindiatracker.com/state_data.json").json()[range(0, 20)]['state'] city1 = requests.get("https://api.covidindiatracker.com/state_data.json").json()[range(0, 20)]['districtData'] data = False except: data = True return render(request, 'covid_app/home.html', {'globrep': globrep, 'countries': countries, 'ind': ind, 'city': city, 'city1': city1}) In this code i use json()[range(0, 20)]['state'] but it is not working please suggest some way to use first o to 20 data of that API. This is my home.html , {% extends 'base.html' %} {% block content %} {{ city }}<br> <br> {% for i in city1 %} {{ i.name }}<br> {{ i.confirmed }}<br><br> {% endfor %} {% endblock content %} please suggest me how to get first 20 data from api using json() method ..... -
after I created multiple models in my django app for the restframwork I stare getting more errs
I created a single model django project then I added tow more models then I got this err RecursionError at /elements/ maximum recursion depth exceeded while calling a Python object then I reinstalled some packages like djangorestframwork-recursion, then I got this err Error at / Incorrect padding Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0.8 Exception Type: Error Exception Value: Incorrect padding Exception Location: //anaconda3/lib/python3.7/base64.py in b64decode, line 87 Python Executable: //anaconda3/bin/python Python Version: 3.7.3 Python Path: ['/Users/apple/Desktop/Trying to clone notionso note taking app with django ' 'and reac1/backend/restapi', '//anaconda3/lib/python37.zip', '//anaconda3/lib/python3.7', '//anaconda3/lib/python3.7/lib-dynload', '/Users/apple/.local/lib/python3.7/site-packages', '//anaconda3/lib/python3.7/site-packages', '//anaconda3/lib/python3.7/site-packages/aeosa'] Server time: Fri, 7 Aug 2020 06:59:57 +0000 also when I ran python manage.py makemigrations i got You are trying to change the nullable field 'text' on components to non-nullable without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Ignore for now, and let me handle existing rows with NULL myself (e.g. because you added a RunPython or RunSQL operation to handle NULL values in a previous data migration) 3) Quit, and let … -
How to incorporate chat feature in django app [closed]
I have a django app for university alumni where they can make accounts. I want to incorporate chat functionality in it so the registered users can chat with each other just like facebook. Any ideas how I can do this. Should I learn django channels or use some third-party library? It is urgent. -
How to show extra dynamic field along with all model fields inside StackedInline Django
I want to display a dynamic link inside StackedInline admin class. How can I do this if the dynamic field is not part of the model. This is my code - class HistoryInline(admin.StackedInline): verbose_name_plural = 'History' model = Import fields = ('link',) extra = 0 readonly_fields = ['link'] def link(self, obj): url = ... return mark_safe("<a href='%s'>click here</a>" % url) class CatalogAdmin(admin.ModelAdmin): list_display = ('__str__', 'created_at', 'updated_at') inlines = [ImportInline, HistoryInline] exclude = ('app') I tried adding the function name inside fields but it didn't work. Also tried list_display but it seems to be not available for StackedInline How can I make it show me all the model fields as well as the extra dynamic link ? -
How to optimize django-rest-framework serializers with multiple queryset at SerializerMethodField()
I am new to django-rest-framework, and I have a project where I have to optimize the response time of an existing API endpoint. Using django-debug-toolbar, found some ways to use prefetch_related() to lessen the SQL queries. The problem is I found that the design of the serializer is to have multiple SerializerMethodField to get its statistics values and using prefetch_related only works on all() but on the second serializer method field with filter() is still being queried for every Class loop. You may see sample code below(this is not the specific code but something like this). serializer.py: class ClassStatisticsSerializer(ModelBaseSerializer): total_sessions = serializers.SerializerMethodField() activity_count = serializers.SerializerMethodField() def get_total_sessions(self, instance): sessions = instance.classactivity_set.all() date = self.context.get('date') if date: sessions = sessions.filter(date=date) if len(sessions) == 0: return None return sessions.count() def get_activity_count(self, instance): activities = instance.classactivity_set.filter(is_present=False) date = self.context.get('date') if date: activities = activities.filter(date=date) if len(activities) == 0: return None return activities.count() class Meta: model = Class fields = ( 'id', 'batch', 'type, 'total_sessions' 'activity_count' ) views.py: class ClassStatisticsList(APIView): def get(self, request, *args, **kwargs): queryset = Class.objects.all().prefetch_related('classactivity_set') serializer = ClassStatisticsSerializer() return Response(serializer, status=status.HTTP_200_OK) In here, when I check the SQL queries on the django debug toolbar, get_total_sessions was being queried once on the …