Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
video call working in localhost using webrtc in reactjs and python django channels for websocket.... but not working in staging?
I had to implement a video call application using webrtc in React JS and used Python django channels in the backend for the web socket connection. The video call is working fine on localhost but not in staging. How do you think I could solve this problem? peer connection, send an offer, send an answer, and ice candidates everything is fine. but in staging, video calls are not working. -
Issues running Django server in MacOS
I am having troubles trying to run a Django server in my Macbook M3 Pro with MacOS Sonoma 14.6.1. When running the command python manage.py runserver the server doesn't start neither shows error. I just receive in terminal the messages: Watching for file changes with StatReloader Performing system checks... System check identified some issues: WARNINGS: general_hydrocarbons.HProject.alliance: (fields.W340) null has no effect on ManyToManyField. tracking_event.TrackingManagement.user: (fields.W340) null has no effect on ManyToManyField. System check identified 2 issues (1 silenced). No errors are shown in the terminal. I have also tried the command python manage.py check, this executes correctly with no errors. I tried running the python manage.py migrate and python manage.py makemigrations commands too. Both are returning the same error: zsh: segmentation fault python manage.py migrate zsh: segmentation fault python manage.py makemigrations I have been working on this project the last 4 months with no problems of this type. Today I changed from anaconda to miniforge and this issue appeared. I also tested running other project built over FastAPI and in this case the project is running correctly. The packages installed in the project are: APScheduler==3.10.4 asgiref==3.6.0 beautifulsoup4==4.12.3 bs4==0.0.2 certifi==2024.7.4 charset-normalizer==3.3.2 crispy-bootstrap5==0.7 Django==4.0 django-ckeditor==6.5.1 django-crispy-forms==2.0 django-filter==23.5 django-js-asset==2.0.0 django-recaptcha==3.0.0 et-xmlfile==1.1.0 idna==3.8 lxml==5.3.0 … -
Operational Error in my Django Project as I can't find out why it is happening
I've been working on one of my projects while learning Django, and it's my first project based on follow-up tutorials. Now, I've almost completed my entire project, but there's one problem that keeps occurring, and I can't figure out why. There's a debug mode enabled, and it claims this is an operational error. So, this problem occurs as I am developing an online commerce shop and have created a conversation app that allows users to talk with the Admin about the items. However, when the user enters the text message and presses the submit button, an error message such as "operational error" appears. Even I can't see the message from the Django admin because it also displays the debug error message there. Clicking up on Contact sellerstatic.net/JdPW4V2C.png) Error Message -
Could Rails implement a django style ORM (with fields and migrations defined from the model?)
I love Rails, except I love the field definition and auto-generated migrations in the the Django ORM. Django model example: class Person(models.Model): name = models.CharField(max_length=200) So the field is defined on the model, and then the migrations are generated from it (with ability to modify them before running). Some other frameworks do this as well. There's lots of benefits, from consistent validation to auto-generated admin/forms, factories, and API. Has anyone seen any packages that do something similar in Rails/Ruby? Are there any reasons this wouldn't work? -
How can I resolve the issue where Django migrations are not applying changes to the database?
I have a Django app and I'm using PostgreSQL for the database. I've added some new properties to my models, and after making these changes, I ran the following commands: python manage.py migrate python manage.py makemigrations A new migration file, 0001_initial.py, was generated with the new properties, such as "hdd_list_remark". However, when I check the database, it seems the migrations are not applied. One of the models with the added properties is: hdd_list_remark = models.TextField( max_length=500, blank=True, verbose_name="HDD lijst opmerking") name = models.CharField(max_length=100, verbose_name="Naam") sort = models.CharField(max_length=100, default='', verbose_name="Soort(Latijn)") slug = models.SlugField(max_length=100, editable=False) cites = models.CharField(max_length=5, choices=CitesChoices.choices, default=CitesChoices.EMPTY, verbose_name="Cites") uis = models.BooleanField(default=False, verbose_name="UIS") pet_list = models.CharField(max_length=3, choices=HDDChoices.choices, default=HDDChoices.EMPTY, verbose_name=" HDD lijst") bird_directive_list = models.CharField(max_length=13, blank=True, choices=BirdDirectiveChoices.choices, default=BirdDirectiveChoices.EMPTY, verbose_name=" Vogelrichtlijnen") Habitat_directive_list = models.CharField(max_length=13, blank=True, choices=HabitatDirectiveChoices.choices, default=HabitatDirectiveChoices.EMPTY, verbose_name=" Habitatrichtlijnen") description = models.TextField( max_length=5000, blank=True, null=True, verbose_name="Beschrijving") feeding = models.TextField( max_length=2000, blank=True, null=True, verbose_name="Voeding") housing = models.TextField( max_length=2000, blank=True, null=True, verbose_name="Huisvesting") care = models.TextField(max_length=1000, blank=True, null=True, verbose_name="Verzorging") literature = models.TextField( max_length=10000, blank=True, null=True, verbose_name="Literatuur") images = models.ImageField( upload_to="media/photos/animals", blank=False, null=False, verbose_name="Foto") category = models.ForeignKey( Category, related_name='animals', on_delete=models.CASCADE, verbose_name="Familie") date_create = models.DateTimeField( auto_now_add=True, verbose_name="Datum aangemaakt") date_update = models.DateTimeField( auto_now=True, verbose_name="Datum aangepast") animal_images = models.ManyToManyField( AnimalImage, related_name='related_animals', blank=True) files = models.ManyToManyField( AnimalFile, related_name='related_animals_files', blank=True) The … -
The sub-items of the 'Products' item in the 'Menu' dropdown are not displayed when clicked
The sub-items of the 'Products' item in the 'Menu' dropdown are not displayed when clicked، he 'فهرست' button works correctly when clicked and opens the dropdown, but when I click on the 'محصولات' item, the dropdown closes. I want the sub-items of 'محصولات' to be displayed when I click on it. he 'فهرست' button works correctly when clicked and opens the dropdown, but when I click on the 'محصولات' item, the dropdown closes. I want the sub-items of 'محصولات' to be displayed when I click on it. -
Model's ForeignKey field rises not-null constraint event with `default=` set
My model : def Maker(models.Model): name = models.CharField() def get_default_maker(): default_brand, created = Maker.objects.get_or_create(name="noname") return default_brand.pk class Item(models.Model): maker = models.ForeignKey( Maker, verbose_name="Maker", on_delete=models.SET(get_default_brand), default=get_default_maker ) I have a Maker instance-plug "noname". I would like to assign it on Item creation if maker field not set (in form). But whenever I try to create an Item without setting maker field I get psycopg2.errors.NotNullViolation: null value in column "maker_id" of relation "stock_management_item" violates not-null constraint. Ofcourse, I can manage that in view/form but I would like to understand why default value won't work. -
Access geonode api via client
I'm encountering an issue with authentication in GeoNode and could use some help. I've enabled it by setting: LOCKDOWN_GEONODE=True However, I need to access the API (.../api/v2/...) through a client, both for frontend clients in Django templates and in pure code. When I activate the lockdown, any API call is redirected to the login page, regardless of the authentication method I use. I've tried BasicAuth and token authentication (by adding REST_FRAMEWORK TokenAuthentication), but nothing seems to work. The only workaround I've found is to add the API urls to AUTH_EXEMPT_URLS, and create my own middleware to intercept requests. But that doesn't seem like the correct approach. -
Pointing a Django Project to my Purchased Domain in Google Cloud
I bought domain from GoDaddy and am hosting it in a bucket(which has the same name as my domain) in a project on Google cloud. In the bucket, under 'edit website configuration' I added a simple html page in the field called ' Index (main) page suffix'. That html comes up correctly when I go to my domain on the browser. So everthing works as expectd. The problem is that I want to deploy a Django project(with several apps in it) to my domain instead of the simple html. There are many tutorials that show how to deploy a Django project on Google Cloud but they all end up giving you a domain that they(or Google Cloud) assigns. I don't want Google Cloud generated domain but want the project deployed on my purchased domain. How do I make that work? It seems like it shouldn't be hard so I'm guessing there is a simple 'trick' that I haven't been able to find. I went through several tutorials on Django deployment on Google Cloud. I even deployed one of the small examples from one tutorial. But it has a Google Cloud generated domain name which is not what I want. -
Pass data to django framework using javascript (no jquery)
I have a dropdown list that I got from an uploaded CSV file from Django that I want to pass back to a different Django view with javascript when selected. I keep getting a 404 error (index.js:9 POST http://127.0.0.1:8000/gui_app/%7B%%20url%20%22get_selection%22%20%%7D 404 (Not Found) (anonymous) @ index.js:9 ) when I click on the select button after I choose a value from the dropdown. From what I understand reading the error message, the issue seems to be coming from javascript not being able to render the url the correct way. What's the correct way to pass the url in javascript so that javascript recognizes it and passes the data to the view? Here's my code below index.js let signalSelectButton = document.getElementById("signalSelectButton") const url = loacation.href('/get_selection/') signalSelectButton.addEventListener("click", function() { console.log("clicked") const selectedValue = document.getElementById("signalSelect").value console.log(selectedValue) fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' }, body: JSON.stringify({selected_value: selectedValue}) }) .then(response => { if (!response.ok) { throw new Error('Network response was not ok') } return response.json() }) .then(data => { console.log(data) document.getElementById('response-message').innerText = data.message }) .catch(error => {console.error('Error:', error)}) }) views.py from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.conf import settings from django.core.files.storage import FileSystemStorage from .forms … -
can't login to my django website on phone browser but i can login to accounts created on a phone after deployment on railway
i can login into accounts created on pc using a pc but not a phone and i can login into accounts created on the phone using a phone but not a pc i dont know what settings are involved to fix this im not using a custom user model just the User model of django -
Django, how to get annotated field of related model
For example, the Invoice model has a project field that points a ForeignKey to the Project model, Project has a custom ProjectManager that has get_queryset defined, in get_queryset I do: super().annotate(display=...) and when I want to get this annotated field through Invoice: Invoice.objects.filter(project__display__iregex=...) then an error occurs that project does not have a display field, how can I make it so that the related models take fields from some queryset, this is get_queryset() for us Django 4.2.4 Python 3.10 To take annotated fields I use Subquery: Subquery(models.Project.objects.filter(id=OuterRef("project_id")).values_list("display")) but because of this the request is executed very slowly. -
django dynamic content not appearing [closed]
I have been tyring to create a dynamic carousel that displays title and detail of projects. but the content is not appearing besides the fact that it loads in the inspection tools. <div id="carouselExampleCaptions" class="carousel slide" > <div class="carousel-indicators"> {% for p in projects %} <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="{{ forloop.counter0 }}" {% if forloop.first %}class="active" aria-current="true"{% endif %} aria-label="Slide {{ p }}"></button> {% endfor %} </div> <div class="carousel-inner"> {% for p in projects %} <div class="carousel-item {% if forloop.first %}active{% endif %}"> <img src="..." class="d-block w-100" alt="..."> <div class="carousel-caption"> <h5 class="title" style="color: #ffffff;">{{ p.title }}</h5> <p>{{ p.detail }}</p> </div> </div> {% endfor %} </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="prev"> <span class="carousel-control-prev-icon" ></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="next"> <span class="carousel-control-next-icon" ></span> <span class="visually-hidden">Next</span> </button> </div> I have been trying to resolve this for a day. image -
Django queryset count with zero
I have this Django Model : class Survey(models.Model): call = models.OneToOneField(Call, null=True, related_name='survey', on_delete=models.CASCADE) service = models.ForeignKey(Service, related_name='survey', null=True, on_delete=models.CASCADE) when_start = models.DateTimeField() when_end = models.DateTimeField() I would like to obtain the number of calls per service over a time slot I tried this : start = datetime.datetime(2024, 6, 17, 0, 0) end = datetime.datetime(2024, 6, 17, 23, 59, 59) services = <QuerySet [<Service: S1>, <Service: S2>, <Service: S3>]> Sondage.objects.filter(service__in=services, when_start__range=(start, end)).values('service__name').annotate(nb=Count('call')) result : <QuerySet [{'service__name': 'S1', 'nb': 50}, {'service__name': 'S2', 'nb': 119}]> But I would like to have this (0 for "S3" service): <QuerySet [{'service__name': 'S1', 'nb': 50}, {'service__name': 'S2', 'nb': 119}, {'service__name': 'S3', 'nb': 0}]]> I read several notes that referred to "Coalesce" but I can't seem to use it correctly -
Django, how to create ForeignKey field when .annotate?
I wanted to create a ForeignKey field in Django using .annotate, but I couldn't find any option for it, maybe it doesn't exist. I just want to LEFT JOIN a specific model with a specific condition. But now I have to do it like this: queyrset = Invoice.objects.annotate(provided_amount=Subquery(InvoicePayment.objects.filter(invoice_id=OuterRef("id"), date=timezone.now().date())) queryset.first().provided_amount But I want it like this: queryset = Invoice.objects.annotate(invoice_payment=...) queryset.first().invoice_payment.provided_amount I could do it using property, but I don't want to do it like that, I would like to do everything in one query. Maybe there is a library for this? Django - 4.2.4 Python - 3.10 I tried creating a SQL VIEW and binding it to the model with managed = False, but it's not very convenient to do that every time. -
What is the replacement of RelatedFilter in newer versions of django_filters?
we have a Django project version 2.0.4, now i am trying to upgrade it to 3.1 the project use djangorestframework-filters, but now this package hasn’t been actively maintained. the problem is one of our FilterSet use RelatedFilter, and i can't find any good replacement for it. the relationship to another FilterSet is essential for the corresponding api. the small part of FilterSet: class SchoolFilter(filters.FilterSet): students__student__registrations__examination = RelatedFilter( ExaminationFilter, queryset=examination_queryset, ) the ExaminationFilterSet has so many filters. -
Input fields are not being updated after editing them in a crud program in django
//edit.html <form action="/update/{{ rec.id }}" method="POST"> {% csrf_token %} Name: <label> <input type="text" name="title" value="{{ rec.name }}" /> </label> <br/> Marks1: <label> <input type="number" name="mark1" value="{{ rec.mark1 }}" /> </label> <br/> Marks2: <label> <input type="number" name="mark2" value="{{ rec.mark1 }}" /> </label> <br/> Marks3: <label> <input type="number" name="mark3" value="{{ rec.mark1 }}" /> </label> <br/> Marks4: <label> <input type="number" name="mark4" value="{{ rec.mark1 }}" /> </label> <br/> <input type="submit" value="Post" /> </form> //show.html <td><a href="/edit/{{ data.id }}">Edit</a></td> //views.py def edit(request, id): ob = Student.objects.get(id=id) return render(request, 'edit.html', {'rec': ob}) def update(request, id): ob = Student.objects.get(id=id) ob.name = request.POST.get('name') ob.marks1 = request.POST.get('marks1') ob.marks2 = request.POST.get('marks2') ob.marks3 = request.POST.get('marks3') ob.marks4 = request.POST.get('marks4') ob.save() return redirect("/show") //urls.py path('edit/<int:id>', views.edit), path('update/<int:id>', views.update), Whenever I hit the edit button and enter the new details, the name field becomes blank and the marks field get initialized to 0; -
Django application deployed on Ubuntu server redirects to login page after successful login
I have deployed django on ubuntu 22 server with nginx as the application server, but when I login in to the system and on each request I get redirected back to the login.` if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") logger.debug(f"Attempting to authenticate user {username}.") user = authenticate(username=username, password=password) if user is not None: logger.debug(f"Authenticated user {username}.") login(request, user) if user.role == 'STAFF': return redirect("sales:sales_list") elif user.role in ["MANAGER", "SUPERVISOR",]: return redirect("authentication:manager_dashboard") elif user.role in ["ADMIN", "GENERAL", "CEO"]: return redirect('master:index') this is how I did the authentication` class SalesListView(ListView): """ View for displaying sales transactions. Requires user to be logged in and have specific roles (STAFF, MANAGER, ADMIN, SUPERVISOR, CEO). Displays sales data based on user role and branch. """ template_name = "manager/purchase/sales.html" model = Sale context_object_name = "sales" def dispatch(self, request, *args, **kwargs): """ Custom dispatch method to handle role-based template selection. Sets different template names based on the user's role. """ user = request.user if not user.is_authenticated: # If not authenticated, redirect to login page messages.error(request, 'You need to log in first!', extra_tags="danger") return redirect('authentication:login') self.branch = user.branch.id self.user_role = user.role print(f"User branch {self.branch} : user role {self.user_role}") if self.user_role == 'STAFF': self.template_name = 'team_member/sales/sales.html' # Set … -
sass.CompileError: File to import not found or readable
I am working on a django project and i decide to use django-simple-bulma but anytime run Python manage.py collectstatic i keep getting sass.compilererror Traceback (most recent call last): File "C:\Users\DIAWHIZ\desktop\themiraclemovement\manage.py", line 22, in <module> main() File "C:\Users\DIAWHIZ\desktop\themiraclemovement\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\DIAWHIZ\desktop\themiraclemovement\tmmenv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\DIAWHIZ\desktop\themiraclemovement\tmmenv\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\DIAWHIZ\desktop\themiraclemovement\tmmenv\Lib\site-packages\django\core\management\base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\DIAWHIZ\desktop\themiraclemovement\tmmenv\Lib\site-packages\django\core\management\base.py", line 459, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DIAWHIZ\desktop\themiraclemovement\tmmenv\Lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 209, in handle collected = self.collect() ^^^^^^^^^^^^^^ File "C:\Users\DIAWHIZ\desktop\themiraclemovement\tmmenv\Lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 126, in collect for path, storage in finder.list(self.ignore_patterns): File "C:\Users\DIAWHIZ\desktop\themiraclemovement\tmmenv\Lib\site-packages\django_simple_bulma\finders.py", line 216, in list files.extend(self._get_custom_css()) ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DIAWHIZ\desktop\themiraclemovement\tmmenv\Lib\site-packages\django_simple_bulma\finders.py", line 187, in _get_custom_css css_string = sass.compile(string=scss_string, output_style=self.output_style) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DIAWHIZ\desktop\themiraclemovement\tmmenv\Lib\site-packages\sass.py", line 725, in compile raise CompileError(v) sass.CompileError: Error: File to import not found or unreadable: []. on line 1:1 of stdin >> @import "[]"; -
Special Characters in Auto Slug Field
I'm trying to find the solution to a problem I encounter when using prepopulated_fields. I use this function to create a slug based on an entered title. However, if I insert special characters (+, -, etc.) in the title the slug cannot pick them up. Do you have any idea how to make these special characters read, so that the slug is consistent with the title? Example: Title | Samsung Galaxy S24+ Slug (should become) | samsung-galaxy-s24+ or something similar This is my current code: models.py class Post(models.Model): titolo = models.CharField(max_length=255) descrizione = RichTextUploadingField('Text', config_name='default', blank=True, null=True) slug = models.SlugField(unique=True) admin.py class PostAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('titolo',)} -
Create smaller pdfs with pdfkit
In my django project, i am creating pdfs in python using pdfkit library. However my pdfs with 15 pages have 16mb size. my lib pdfkit==1.0.0 How can I reduce its size, considering my code above: import pdfkit from django.template.loader import render_to_string my_html = render_to_string('mypath/myhtml.html') pdfkit.from_string(my_html, False) -
Why does my XMLHttpRequest cancel my background task before reloading the page
I'm trying to send a XMLHttpRequest to my backend if a user chooses to reload the webpage while a task is running on the backend. It is to function like this: The user starts the task(translation). If the user decides to reload the page or navigate away they should get an alert that the task will stop if they navigate away. If they still choose to navigate away the request is sent to a stop_task view on the backend. Currently if the user starts to navigate away or reloads the task is terminated once the alert shows instead of after the user confirms that they still want to reload/navigate away. Here is my code JS: wwindow.addEventListener('beforeunload', function (e) { if (isTranslating) { stopTranslation(); e.preventDefault(); e.returnValue = ''; return 'Translation in progress. Are you sure you want to leave?'; } }); function stopTranslaion() { if (isTranslating && currentTaskId) { // Cancel the polling console.log(currentTaskId) clearInterval(pollInterval); // Send a request to the server to stop the task const xhr = new XMLHttpRequest(); xhr.onload = function() { if (xhr.status == 200) { const response = JSON.parse(xhr.responseText); if (response.status === 'stopped') { console.log('Translation stopped'); isTranslating = false; currentTaskId = null; // Update UI to … -
Django-ninja Webhook Server - Signature Error/Bad Request
I am working on a Django application where I have to develop a webhook server using Django-ninja. The webhook app receives a new order notification as described here: https://developer.wolt.com/docs/marketplace-integrations/restaurant-advanced#webhook-server My code below: @api.post("/v1/wolt-new-order") def wolt_new_order(request: HttpRequest): received_signature = request.headers.get('wolt-signature') if not received_signature: print("Missing signature") return HttpResponse('Missing signature', status=400) payload = request.body expected_signature = hmac.new( CLIENT_SECRET.encode(), payload, hashlib.sha256 ).hexdigest() print(f"Received: {received_signature}") print(f"Expected: {expected_signature}") if not hmac.compare_digest(received_signature, expected_signature): return HttpResponse('Invalid signature', status=400) print(payload) return HttpResponse('Webhook received', status=200) For some reason this always returns 'error code 400, bad request syntax' and the two signatures are always different. I am importing the CLIENT_SECRET correctly and I have all the necessary libraries properly installed. Funny enough when I do the same on a test Flask app, I receive the webhook notification correctly without issues. My webhook server is behind ngrok. Any ideas? What am I doing wrong here? Any suggestions? -
Most suitable psycopg3 installation method for a production Django website with PostgreSQL
I'm running a production website using Django with a PostgreSQL database. The official psycopg3 documentation (https://www.psycopg.org/psycopg3/docs/basic/install.html) describes three different installation methods: Binary installation Source installation C extension-only installation Which of these installation methods would be most performant and suitable for a production environment? Are there any specific considerations or trade-offs I should be aware of when choosing between these options for a Django project in production? I'm particularly interested in: Performance implications Stability and reliability Ease of maintenance and updates Any potential compatibility issues with Django -
How to set value for serializers field in DRF
I have a webpage in which I show some reports of trades between sellers and customers.So for this purpose, I need to create an api to get all of the trades from database, extract necessary data and serialize them to be useful in webpage.So I do not think of creating any model and just return the data in json format. first I created my serializers like this : from rest_framework import serializers from django.db.models import Sum, Count from account.models import User class IncomingTradesSerializer(serializers.Serializer): all_count = serializers.IntegerField() all_earnings = serializers.IntegerField() successful_count = serializers.IntegerField() successful_earnings = serializers.IntegerField() def __init__(self, *args, **kwargs): self.trades = kwargs.pop('trades', None) super().__init__(*args, **kwargs) def get_all_count(self, obj): return self.trades.count() def get_all_earnings(self, obj): return sum(trade.trade_price for trade in self.trades) def get_successful_count(self, obj): return self.trades.exclude(failure_reason=None).count() def get_successful_earnings(self, obj): return sum(trade.trade_price for trade in self.trades.exclude(failure_reason=None)) class TradesDistributionSerializer(serializers.Serializer): sellers = serializers.DictField() def __init__(self, *args, **kwargs): self.trades = kwargs.pop('trades', None) super().__init__(*args, **kwargs) def get_sellers(self, obj): sellers = {} for user in User.objects.all(): distributed_trades = self.trades.filter(creator=user) sellers[user.username] = sum( trade.trade_price for trade in distributed_trades) return sellers and then my apiView look like this : from rest_framework.views import APIView from rest_framework.response import Response from trade.models import Trade from report.serializers import IncomingTradesSerializer, TradesDistributionSerializer class IndicatorView(APIView): def get(self, …