Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does creating django objects in a loop burn memory?
I have code like this: for row in PageURL.objects.all(): r = requests.get(row.url) ss = Snapshot() ss.html = r.text ss.pageUrl = row ss.save() I am running out of memory. I believe that the "ss" variable isn't being cleared when looping 1000s of times. Would garbage collection not handle it? It runs fine on my Mac but on Centos 7 it uses more memory, oddly. -
Cannot render a list in template from django view
All my views are being rendered properly but when i try to render a list using iteration nothing is displayed on the page, without error. the view: from django.shortcuts import render from haleys_chemist.models import anti_bacterials from django.http import HttpResponse from .table import anti_bacterials_Table from django_tables2 import RequestConfig from datetime import datetime from django.http import HttpResponseRedirect from .forms import notepadform from django.contrib.auth.decorators import login_required from django.views.generic import TemplateView,ListView class retriever(TemplateView): template_name='index.html' def expiry_days(self,request): expired_drugs= anti_bacterials.objects.all() args={'expired_drugs':expired_drugs} return render (request, self.template_name,args) template(index.html): <h6><i>Drugs about to expire</i></h6> {%for expired_drug in expired_drugs%} <ul> <li>{{expired_drug.Drug_name}}</li> <li>{{expired_drug.expiry_date}}</li> </ul> {%endfor%} </div> model: class anti_bacterials(models.Model): Drug_id= models.IntegerField(primary_key=True); Drug_name= models.CharField(max_length=50); expiry_date= models.DateField(); Price_per_mg= models.DecimalField(decimal_places=2, max_digits=20) i need to list the expired drugs on the left bar. i know i have queried for all objects on the view but still i should get a list of all the objects names and expiry dates. -
How do I translate a url link into a path link in django when creating a dynamic link in an HTML template?
I'm super new at all of this. I'm following a tutorial (this one to be exact: https://www.youtube.com/watch?v=qgGIqRFvFFk) and it uses url() to create the urls and everything. However, the version of django that I downloaded uses path() and I've done pretty okay with translating everything over, but I'm trying to create a dynamic link in my HTML template so that I don't have any links hardcoded into the template. I keep getting an error though. This is my code: <form action="{% path 'music.favorite', album.id %}" method="post"> It's giving me an error saying 'Invalid block tag' and highlighting everything between the {% %} like there's something wrong with the python. I've been staring at this for so long. Someone save me. -
Heroku: ModuleNotFoundError: No module named 'lending'
It pushes successfully, but it doesn't run once I go to the website. My full error is here. My Procfile is web: gunicorn p2plending.p2plending.wsgi:app My requirements.txt is psycopg2==2.7.6.1 djangorestframework==3.9.2 Pillow==6.0.0 requests==2.21.0 factory_boy==2.11.1 django-filter==2.1.0 django-rest-auth==0.9.5 django-heroku gunicorn -
Django user not defined errors
I still can't understand why i am getting NameError: name 'User' is not defined. I am using a custom user model with settings.py updated appropriately with AUTH_USER_MODEL = 'accounts.User' models.py from django.conf import settings from django.contrib.auth import get_user_model class Profile(models.Model): username = models.ForeignKey(User, on_delete= models.CASCADE) class User(AbstractUser): role = models.CharField(max_length=50) But strangely when i use: from django.contrib.auth import get_user_model User = get_user_model() i get the error: AUTH_USER_MODEL refers to model 'accounts.User' that has not been installed -
How to handle login/logout flow for multi users working on the same hardware computer
We have a classic web application accessed from physical shop with their computer, using browser. We build user role (owner and staff) and credentials so far normal web application. But we notice that lot of shop don't use it the way we except. They create one owner account and everybody use the same account. As main shops have only one computer and staff don't want to logout and type their login/password each time they take an order or need to search for information. I know that POS system have code bar reader and staff can scan their code-bar before registering an order but for our web application we don't have this hardware. So I wonder if there's some best practice, library, example or idea on how to handle this case. Thanks for reading. -
Serving static files with digitalocean
I am using DigitalOcean to serve my static files for my website. I have used Django and Postgres for database. I deployed my site with a DigitalOcean droplet, uploaded my static files in the DigitalOcean Spaces (I verified that they are indeed there), and updated my settings.py code to update my database information. CDN is enabled and CORS is configured. I tested the site using gunicorn (step 7 of tutorial), but my website is still simply html text with no css styling from my static files. When I clicked "inspect element > sources" I can see that href is indeed https://[my DigitalOcean Spaces information] What else do I need to update to be able to serve my static files? Tutorial link:https://www.digitalocean.com/community/tutorials/how-to-set-up-a-scalable-django-app-with-digitalocean-managed-databases-and-spaces -
Django AttributeError: module 'cal.views' has no attribute 'index'
I have a problem to create a calendar with django, this code is similar a tutorial, but the problem is in folder cal/views my code with django detects attribute errors and I no longer know what could be wrong, I already checked the files in the "cal" folder pls help me in my code :( this is the code in descubretepic/cal/views from datetime import datetime from django.shortcuts import render from django.http import HttpResponse from django.views import generic from django.utils.safestring import mark_safe from .models import * from .utils import Calendar class CalendarView(generic.ListView): model = Event template_name = 'cal/calendar.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # use today's date for the calendar d = get_date(self.request.GET.get('day', None)) # Instantiate our calendar class with today's year and date cal = Calendar(d.year, d.month) # Call the formatmonth method, which returns our calendar as a table html_cal = cal.formatmonth(withyear=True) context['calendar'] = mark_safe(html_cal) return context def get_date(req_day): if req_day: year, month = (int(x) for x in req_day.split('-')) return date(year, month, day=1) return datetime.today() my code in descubretepic/cal/urls from datetime import datetime from django.shortcuts import render from django.http import HttpResponse from django.views import generic from django.utils.safestring import mark_safe from .models import * from .utils import Calendar class CalendarView(generic.ListView): … -
Is it possible to use inline CSS to reference dynamic images in Django?
Sorry if the title was a bit unclear, I couldn't think of any other way to phrase it. So I want to know if it's possible to use inline CSS (<div class="" style="background-image: url();" and put the dynamically created images in there. So if I want a user to upload a banner, I want the background image of the div to be the image. Is this possible? So for example The user uploads a photo and it goes to /media/ Then normally to reference it, I would do <img class="user-image" src="{% user.userprofile.image.url %}"> However, what if I wanted to set it as a background image. In the CSS document, I want to do this: .user-image-div { background-image: url({% user.userprofile.image.url %}) } However, this doesn't work. So my question is, is it possible to use inline CSS in the HTML document to get around this? So like <div class="user-image-div" style="background-image: url({% user.userprofile.image.url %};)"> <!-- code here --> </div> Would this work? I don't have access to Django at the moment, so I will be able to test it out in a few days -
Comparing javaScript values then redirect to another url if true
problem on comparing values and redirecting to another page ,, values are string and integer "CharFields" .. else statement works fine but the if statement when i type it correct the page just refreshes and nothing happens.. and if possible i want to make that commented img replace the button,, thx any way :) i made java function to get variables from a user input trcode and made django print the model in an input value those two works fine i tested them with printing ,, the problem is in comparing the values and redirecting to the another url function readText () { var value1 = document.getElementById("trcode").value; var value2 = document.getElementById("trfcode").value; if (value1 === value2) { location.href="http://127.0.0.1:8000/myposts";} else { alert("You typed: " + "Wrong Password");} }``` ``` ### tried to use=> if (value1.equals(value2)){ #### NOTHING CHANGED SAME PAGE REFRESH ### }### ``` ```html <form onsubmit="return readText();"> <tr><td height="18" class="subheaderboldtext"> Enter Code: <input id="trcode" maxlength="8" class="box"> <input class="submit" type="submit" value="SUBMIT"> {# <img src="/static/guest/images/querybutton.png" alt="Query Button">#} </form></td></tr> <button id="trfcode" value="{{ user.profile.trf_code }}">z</button> when the user type wrong password alert appears and when he write it right he get redirected to a certain page on the site -
Safe filter Still Displays HTML Tags
I have added CKEditor to my django project, but the text is still showing HTML tags. Despite the fact that I have the safe filter inserted following my content variable. Am I missing the reason that this will not escape the HTML tags? Here is my model: class Post(models.Model): title = models.CharField(max_length = 100) content = RichTextUploadingField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='post_pics') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) Here is my form template: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class='border-bottom mb-4'>New Post</legend> {{ form.media }} {{ form | crispy }} </fieldset> <div class="form-group"> <button type="submit" class="btn btn-outline-info">Upload</button> <a type="submit" class="btn btn-outline-secondary" href="/">Cancel</a> </div> </form> Here is my post detail template: <article class="media content-section"> <img src="{{ post.author.profile.image.url }}" alt="profile photo" class="rounded-circle article-img"> <div class="media-body"> <img src="{{ post.image.url }}" class="post-img"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' object.author.username %}">{{ object.author }}</a> <small class="text-muted">{{ object.date_posted | date:'F d, Y'}}</small> {% if object.author == user %} <div> <a href="{% url 'post-update' object.id %}" class="btn btn-outline-secondary btn-sm mt-1 mb-1">Edit</a> <a href="{% url 'post-delete' object.id %}" class="btn btn-outline-danger btn-sm mt-1 mb-1">Delete</a> </div> {% endif %} </div> <h2 class='article-title-detail'>{{ object.title }}</h2> <p class="article-content">{{ … -
Website suddenly stopped loading 'Incomplete response received from application'
I am new to using Django and have recently put a website on a cloud managed server. Everything has been working fine for about a month or so. However, a day or so ago it is no longer loading and comes up with the error 'Incomplete response received from application'. In the console of my browser it also says it is a 502 error. I have looked and tried a few things online, but it seems that this problem can be caused by a few different things. I also tried looking at the passenger error.log file, but that didn't come up with anything. I was wondering if anyone has any tips, or can send me in a good direction to find out whats going on, as I haven't touched the files since they were uploaded. Thanks in advance. -
good practices of VBC views
I have a question about class-based views. I have the following view: class UserCourseListView(ListView): model = User template_name = 'courses/user_course_list.html' def get_queryset(self): user_inscriptions = self.request.user.get_inscriptions.all() courses = [inscription.course for inscription in user_inscriptions] return courses The purpose of the view is to obtain a list of the courses in which the user who logged in at that time has registered. And be able to access that data in context (in the template). The doubt I have is the following: The model class attribute is theUser model and in the get_queryset estoy method returning instances of theCourse model, which does not make much sense. And my question is, is it good practice to do this? Is there another better way to do it with class-based views? Another way I came up with it and that is more consistent is with a function-based view, but it doesn't convince me much: def user_course_list(request): user_inscriptions = request.user.get_inscriptions.all() courses = [inscription.course for inscription in user_inscriptions] return render('courses/user_course_list.html', {'courses': courses}) Since Django documentation recommends that we use class-based views as much as possible. -
Data from SAP to Django
How to stream data from SAP into a django webapp? Is there any documentation? Do I need an api from the sap api management system? Can I use sqlite3 as a database in django? Thank you for any help -
Django how to display subquerys in Template
My view: credits = Credit.objects.filter(account=OuterRef('pk')).values('account_id').annotate(sum_credits=Sum('amount')) debits = Debit.objects.filter(account=OuterRef('pk')).values('account_id').annotate(sum_debits=Sum('amount')) dif = Account.objects.annotate(credit_sum=Subquery(credits.values('sum_credits')),debit_sum=Subquery(debits.values('sum_debits')),balance=F('credit_sum') F('debit_sum')).values_list('name', 'balance') My template: {% for account in dif %} <tr> <td>{{ account }}</td> <td></td> <td></td> <td></td> </tr> {% endfor %} result : ('andrea', 10) ('mosca', 20) how to remove the parentheses? -
How do I properly condense this Python IF statement?
I am pretty new to Python, and trying to find a better way to code this. There has to be a way but just not sure how to do it. The two queries are essentially the same, so there has to be a way to reduce. Is there a more efficient way to do this? if set_date is not None: params = {CarTow.ACCEPTED,CarTow.UNCONFIRMED} if is_rejected != 'true': query = query\ .filter(createddate__lte=set_date) \ .car_statuses(CarTow.ACCEPTED) \ .order_by('-createddate') else: query = query\ .filter(airdate__lte=set_date) \ .car_statuses(CarTow.ACCEPTED,CarTow.UNCONFIRMED) \ .order_by('-createddate') return query Sorry if this is a simple question, newbie here. -
Django. JSON response not working as expected
In Django, I am simply sending some JSON back when a user makes a POST request to my server. I am sending different JSON responses depending on the information the user inputs to my api endpoint. (I am using POSTMAN to test this) My API checks if the passwords a user supplies match, and if so sends a success message, however if not send a failure message. If they match or don't match, the same JSON is always sent back. Which is not wanted. Here is my code: def signup(request): if request.method == 'POST': if request.POST.get('password1') == request.POST.get('confirmPassword'): return JsonResponse({'message': 'Well Done'}) print('Success') else: print('Do not match') return JsonResponse({'error': 'Password fields do not match'}, status=400) Postman input: { "password1": "test123", "confirmPassword": "deedeedde" } RESPONSE: { "message": "Well Done" } -
Render ValidationError in template
I am making a page for adding products to the web shop by the user, and I am having troubles with displaying ValidationError in my template. The ValidationError is raised if selected category isn't the most specific category to select. To select a category, the user has to go trough chained dependent combobox selection, where you start with one combobox for main category and once you select main category, another <select> appears for selecting a subcategory, and so on until the innermost subcategory is selected. category is a field on my base Product model (from which other models, such as Book or Shoes, inherit) and isn't listed in ModelForms' inner Meta class fields, thus I can't have clean_category method on my ModelForms. Here is my view: @login_required def product_create_view(request): if request.method == 'POST': main_category = request.session.get('main_category') create_product_form = mappings[main_category](request.POST) if create_product_form.is_valid(): obj = create_product_form.save(commit=False) category = request.session.get('category') if Category.objects.get(id=category).is_leaf_node(): obj.category = Category.objects.get(id=category) obj.save() else: raise forms.ValidationError('Please select most specific category.') return render(request, 'products/product_create.html', { 'categories': Category.objects.filter(parent=None) }) How to render the ValidationError in the template, i.e. how can I have my ValidationError in my {{ field.errors }}? Currently I am seeing a stack trace. -
Python/Django: How to reactivate pipenv after exiting
Please Everybody. I have a little problem with pipenv. For instance, I am work on a Django project and I decided to sleep. I had to shutdown my laptop for some reason. Then i woke up navigated to the project and I open it in VScode again. My question is how to I reactivate the pipenv environment again. I mean something like source bin/activate if you are using virtualenv I use pipenv shell but i want to be sure that is absolutely right. -
How to fix problem with DJANGO_SETTINGS_MODULE?
I am pretty beginner in django and in coding too. Stuck for a while with an error. Will really appreciate if someone's help me!I tried to google it and it gave me a lot of solutions, I tried them but it gave errors too. What should I write to make things done? I took this code from https://www.youtube.com/watch?v=a48xeeo5Vnk&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p&index=2 from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), ] And it gave me this error: File "urls.py", line 21, in <module> path('admin/', admin.site.urls), File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/functional.py", line 256, in inner self._setup() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 529, in _setup AdminSiteClass = import_string(apps.get_app_config('admin').default_site) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/registry.py", line 153, in get_app_config self.check_apps_ready() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 64, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.``` -
Change structure of JSON data for API POST request with Django
I have a Django REST API endpoint with this structure, that I need to post to an external API: { "body": [ "...", "...", "...", ], "title": [ "...", "...", "...", ], "id": [ "...", "...", "...", ] } The first item under 'body' goes with the first under 'title' and 'id', and so forth. The problem I'm having is that the API in question expects JSON data with the following structure: { "texts": [ { "body": "...", "title": "...", "id": "..." }, { "body": "...", "title": "...", "id": "..." }, { "body": "...", "title": "...", "id": "..." }, ], "language": "EN", } And I can't figure out how have my endpoint mirror that structure, with the bodies, titles, and ids grouped together, those groupings nested under texts, and with the language parameter appended at the end. The serializer I'm using in my views.py looks as follows: class MyReasonsSerializer(serializers.Serializer): body = serializers.SerializerMethodField() title = serializers.SerializerMethodField() id = serializers.SerializerMethodField() def get_body(self, obj): return obj.reasons.order_by('transaction_date').values_list('body', flat=True) def get_title(self, obj): return obj.reasons.order_by('transaction_date').values_list('title', flat=True) def get_id(self, obj): return obj.reasons.order_by('transaction_date').values_list('transaction_date', flat=True) class ReasonsData(RetrieveAPIView): queryset = Market.objects.all().prefetch_related('reasons') authentication_classes = [] permission_classes = [] serializer_class = MyReasonsSerializer Thanks in advance for any advice! -
slider menu in django suit not working in google chrome
Suddenly with a Google Chrome update, the slider menu does not work in django suit, with python2, but in other browsers such as safari if it works, I don't know why it should, or how it can be fixed -
"ERROR: Command errored out with exit status 1" while trying to perform "pip install mod-wsgi" in command prompt (Windows 10)
I want to deploy my django app using apache and mod_wsgi on Windows 10. I have Python 3.7 (64-bit) and Apache 2.4.41 Win64. I open up the admin command prompt and type "pip install mod-wsgi" The following occurs: Collecting mod-wsgi Using cached https://files.pythonhosted.org/packages/26/03/a3ed5abc2e66c82c40b0735c2f819c898d136879b00be4f5537126b6a4a4/mod_wsgi-4.6.7.tar.gz Installing collected packages: mod-wsgi Running setup.py install for mod-wsgi ... error ERROR: Command errored out with exit status 1: command: 'c:\program files\python37\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\jason\\AppData\\Local\\Temp\\pip-install-5snwyezc\\mod-wsgi\\setup.py'"'"'; __file__='"'"'C:\\Users\\jason\\AppData\\Local\\Temp\\pip-install-5snwyezc\\mod-wsgi\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\jason\AppData\Local\Temp\pip-record-6qml1kb3\install-record.txt' --single-version-externally-managed --compile cwd: C:\Users\jason\AppData\Local\Temp\pip-install-5snwyezc\mod-wsgi\ Complete output (33 lines): c:\program files\python37\lib\distutils\dist.py:274: UserWarning: Unknown distribution option: 'bugtrack_url' warnings.warn(msg) running install running build running build_py creating build creating build\lib.win-amd64-3.7 creating build\lib.win-amd64-3.7\mod_wsgi copying src\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi creating build\lib.win-amd64-3.7\mod_wsgi\server copying src\server\apxs_config.py -> build\lib.win-amd64-3.7\mod_wsgi\server copying src\server\environ.py -> build\lib.win-amd64-3.7\mod_wsgi\server copying src\server\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\server creating build\lib.win-amd64-3.7\mod_wsgi\server\management copying src\server\management\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\server\management creating build\lib.win-amd64-3.7\mod_wsgi\server\management\commands copying src\server\management\commands\runmodwsgi.py -> build\lib.win-amd64-3.7\mod_wsgi\server\management\commands copying src\server\management\commands\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\server\management\commands creating build\lib.win-amd64-3.7\mod_wsgi\docs copying docs\_build\html\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\docs creating build\lib.win-amd64-3.7\mod_wsgi\images copying images\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\images copying images\snake-whiskey.jpg -> build\lib.win-amd64-3.7\mod_wsgi\images running build_ext building 'mod_wsgi.server.mod_wsgi' extension creating build\temp.win-amd64-3.7 creating build\temp.win-amd64-3.7\Release creating build\temp.win-amd64-3.7\Release\src creating build\temp.win-amd64-3.7\Release\src\server C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Ic:\Apache24/include "-Ic:\program files\python37\include" "-Ic:\program files\python37\include" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files … -
Attaching profile to user model in django
I am trying to add some extra information to my user model...via the one-to-one link example here: https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#onetoone So I took their example: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) Implemented it on my own in an /accounts app that seemed to of showed up in my application once I got authentication and authorization stuff working in my djanog app. So the models.py in my /accounts looks like: class APOUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) institution = models.ForeignKey("mainpage.InstitutionMember", on_delete=models.PROTECT) on_site_status = models.ForeignKey("mainpage.SiteStatus", on_delete=models.PROTECT) refer_to_as = models.TextField(max_length = 30, blank=True) #if the above is custom room_preference = models.ForeignKey("housing.Room", on_delete=models.PROTECT) I can say: python3 manage.py makemigrations accounts It works, but when I try to run a python3 manage.py migrate it chokes with an error about a lazy reference in one of my other app's models: ValueError: The field housing.HousingRequest.user was declared with a lazy reference to 'accounts.apouser', but app 'accounts' isn't installed. I don't recall ever installing the accounts it seemed to always be there in my settings given by what I guess was this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', … -
Passing filtering options to a nested serializer in django DRF
assuming I have the following models and serializers : Models: class Album(models.Model): album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE) title = models.CharField(max_length=100) duration = models.IntegerField() and the following serializers : class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ['order', 'title', 'duration'] class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True, read_only=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] I would like to write a view that by getting a duration value will return a list of albums containing the tracks that the duration is equal to the given duration value. Assuming I have an album : a - of John, track1, duration : 60 track2, duration : 120 track3, duration : 60 b- of Mike, track1, duration : 60 track2, duration : 120 If I'll reach my endpoint with the value duration: 60, I want the following to return: [album : a, track1, duration : 60 track2, duration : 120 track3, duration : 60 album : b, track1, duration : 1:00 ] The main issue I am having is that I can't control the queryset of a nested serializer, what I would like to be able to do, is to pass the duration value …