Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get count of users registered pey day in django app
I need to create a simple chart (using chart.js),so the should chart like this: On the Y-axis - the number of registered users,X-axis - date Screen below: My model: class User(AbstractBaseUser, PermissionsMixin): uid = models.CharField(max_length=36, unique=True, default=make_uid) email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255, unique=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) activation_token = models.CharField(null=True, blank=True, max_length=100) date_joined = models.DateTimeField(default=now, editable=False) View: @staff_member_required() @login_required() def index(request): users = User.objects.all() context = { "users": users, "users_count": users.count } return render(request, "backoffice/backoffice_index.html", context) Template part with chart: <script> $(document).ready(function () { var ctx = document.getElementById("myChart").getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: [{% for user in users %} '{{ user.date_joined }}', {% endfor %}], datasets: [{ label: '# of users registered per day', data: [], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); }); </script> <canvas id="myChart" … -
Django : "internal" (not views) functions. How to redirect and pass message when no Request?
I have understood how requests and URLs work in Django. I understood either that most of thing works with request. But coming from PHP, there is something missing in my Django understanding. I need to create (what I'm calling) internal functions or classes for doing repetitive tasks. Sometimes, some of them are even interconnected. In the present case : check if a CSV file is (still) existing. Otherwise, I want to stop the execution of my view and redirect to a page with an alert. However, I've read everywhere that messages system in Django works with request. But in my case, I ain't got request. So, what is the solution for passing messages with redirect or HttpResponseRedirect (or something else I don't already know) without request ? Do I need to always attach my functions on an URL and treat them like a view ? After long researches, still haven't found those answers. -
how to post data in a nested serializer in Django rest framework
I am working on an app and need help I want to authenticate LinkedIn and save the access token in a table and then collect the LinkedIn user details in another table below is my model.py class LinkedInUserCode(models.Model): """ Credentials for the user to give access to LinkedIn. """ user = models.OneToOneField(User, on_delete=models.CASCADE) token = models.CharField(max_length=1024) expires_in = models.IntegerField() def __str__(self): return f'{self.token}' class Meta: db_table = 'linkedin_user_code' verbose_name_plural = "LinkedIn User Codes" class LinkedInProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) linkedin_id = models.CharField(max_length=1024, blank=True, null=True) first_name = models.CharField(max_length=1024, blank=True, null=True) last_name = models.CharField(max_length=1024, blank=True, null=True) profile_image_url = models.CharField(max_length=1024, blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.linkedin_id}' class Meta: db_table = 'linkedin_profile' verbose_name_plural = "LinkedIn Profiles" I am using a nested serializer and this is my serialiser class LinkedInProfileSerializer(ModelSerializer): """ Serializer for the LinkedInProfile model. """ id = IntegerField(required=False) user = ReadOnlyField(source='user.email') linkedin_access = ReadOnlyField(source='linkedin_access.token') class Meta: model = LinkedInProfile fields = '__all__' def create(self, validated_data): """ Create a new LinkedInProfile instance. """ return LinkedInProfile.objects.create(**validated_data) def update(self, instance, validated_data): instance.linkedin_id = validated_data.get('linkedin_id') instance.first_name = validated_data.get('first_name') instance.last_name = validated_data.get('last_name') instance.profile_image_url = validated_data.get('profile_image_url') instance.linkedin_access = validated_data.get('linkedin_access') instance.save() return instance class LinkedInUserCodeSerializer(ModelSerializer): user = ReadOnlyField(source='user.email') profiles = LinkedInProfileSerializer(many=True, read_only=True) class Meta: … -
How to use Javascript variable in an if condition in Django template?
I am currently working on a django template wherein I want to use a javascript variable in the if condition. My code is as follows {% extends 'base.html' %} {% block content %} <br> <div class="buttonRow"> {% for t in tickerList %} <button class="btn btn-dark" onclick="changeChart(this.value)" value="{{ t }}">{{ t }}</button> {% endfor %} </div> <br><br> {% if {{ currentTicker }} %} {{ currentTicker |safe }} {% else %} <p>NO Graph</p> {% endif %} {% endblock %} <style> .buttonRow { width: 100%; float: left; border: solid 1px blue; text-align: center; } button { background: black; color: white; } </style> <script> var currentTicker = {{ tickerList.0 }} function changeChart(ticker) { currentTicker = ticker; } </script> Here the dictionary I send from the server-side may look like this { "tickerList" : ["GOOGL","TSLA"], "GOOGL" : (plotly object), "TSLA" : (plotly Object) } Depending on the button clicked by the user I want to change the graph (plotly object) on the screen. As you can I have made the necessary buttons and I change ```currentTicker`` variable but I am not sure how I can change the graph in real-time on the screen when the user clicks the button. Could anyone help with this? -
Django change ListView query based on selected option from dropdown menu without reloading page
I want to create a ListView that displays items from the Inventory model based on the selected Site from the dropdown menu without reloading the page as shown here: I tried passing in site.pk into the ListView filter which comes from the HTML template, but I believe this would reload the page and would pass it into the url (we prefer it not to). inventory.html {% for site in data.project_sites %} <a href="{% url 'inventory:list-inventory' site.pk %}"> <option value="{{site.pk}}">{{ site.siteName }}</option> </a> {% endfor %} views.py class InventoryListView(LoginRequiredMixin, generic.ListView): ... model = Inventory def get_queryset(self): qs = { "inventory": Inventory.objects.filter(id=self.request.GET.get('site.pk')), "project_sites": Site.objects.all(), } return qs I understand that this requires Javascript, but my group does not have much experience with Javascript and we have a short timeline for this. -
Unble to query django model using regex on live web server
I am working on querying django models using react axios get method and using regular expression to get the desired results. There is strange behaviour when request is made by the react axios get method. So, when I test on my local enviroment it works fine but when I put it on live web server it gives me 500 Internal Server Error. My tastypie resource: class ReportEmployeeResource(ModelResource): class Meta(CommonMeta): queryset = Employee.objects.all() resource_name = 'report-employee' filtering = { 'fname': ALL, 'lname': ALL, 'date': ALL } My Django Model: class Employee(models.Model): fname= models.CharField(max_length=50) lname = models.CharField(max_length=50) date = models.DateField(db_index=True) class Meta: db_table = 'employee' unique_together = ('date','fname') My react axios get request: axios.request({ method: 'GET', url: generateUrl('report', 'report-employee', [ { key: 'lname__regex', value: '^((?!\\w+).)*$' }, { key: 'date', value: startDate.format('YYYY-MM-DD') }, ]), headers: { 'Content-Type': 'application/json', }, }).then(response => { console.log(response.data); }); I have to use regex to check if lname has no words present in it. The request is working on local perfectly, but after putting it on live server it does not work. When I removed lname__regex from the url it returns the response. I am using Django 3.1.13 version, react 16.12.0 version, Live server is AWS EC2 with … -
Multiple filter option in Django Admin Charfield
How to filter multiple option in a admin.py, Models.py banana_name = models.CharField(max_length=255, verbose_name=_("Banana Name")) Admin.py list_filter = [ "banana_name", ] in banana_name there are multiple banana name , right now i can select one banana name at a time or all or none at a time. -
How to add collation in indexes for mongodb?
I work with Mongoengine in Django, got task to sort by first_name, last_name fields ignoring case and leading whitespaces that is why add collation in queryset: collation = dict( locale='en', caseLevel=False, caseFirst='off', strength=3, numericOrdering=True, alternate='shifted', maxVariable='space', backwards=False, ) return queryset.collation(collation).order_by('first_name','last_name') Unfortunetly, my queryset takes too long time I want to speed up it, so start to read about mongodb indexes, but don't understand how add it properly, I tried this: models.py class User(UpdatedAtTimestampMixin, Document): first_name = fields.StringField(null=True, db_field='firstName') last_name = fields.StringField(null=True, db_field='lastName') meta = 'collection': 'users', 'strict': False, 'indexes': [ ['-is_active', 'first_name', 'last_name'], ], } The main question is How to include collation in indexes? And will it work with null=True Field? -
Deploy Django app on Heroku and keep url from previous site
I've created a website for a client who had already a previous website. I know how to deploy it on Heroku, but what I have to do keep the URL of their previous website? What kind of datas they have to give me? And How process? Sorry if it looks a little stupid but I never deploy a website before, only created somes for my personal use. Thank you in advance -
Is it possible to customize the Django Admin page?
How do you customize the Django Admin Page, using your own custom page? I haven't tried anything yet, still using the default page -
Django Rest Framework send queryset to serializer try SlugRelatedField
Hi i am trying to send ordered query to my parent serializer try slug related field but i am getting "Object of type Supplier is not JSON serializable". i have also tried to make a "serializers.SerializerMethodField()" but i am getting the same error. is there a way to do something similar? in my model i am ordering it by name so i need to do another query so that i can order it by last visited. Should i make new model serialzier and make query there and pass it to parent serializer? models.py last_visited = models.DateTimeField(auto_now_add=True, null=True) class Meta: ordering = ["name"] @property def last_4_visited(self): return Supplier.objects.order_by('last_visited')[3] serializer.py suppliers = serializers.SlugRelatedField(slug_field='last_4_visited', many=True, read_only=True) -
Why I can not display two listviews in one template?
I am working on a Django project where admin can upload a hero banner to the site and can also upload a notification on the home page of the site. So I made listviews for listing the two HeroListView and NotificationListView for that. But the second one is not appearing in the page. Please tell me how to solve this issue. This is the models.py file from django.db import models class Hero(models.Model): image = models.ImageField(upload_to="heros/") class Notification(models.Model): notification = models.CharField(max_length=200) This is the views.py file. from django.views.generic import ListView from .models import Hero, Notification class HeroListView(ListView): model = Hero template_name = "home.html" context_object_name = "hero_list" class NoticficationListView(ListView): model = Notification template_name = "home.html" context_object_name = "notification_list" this is the app/urls.py file from django.urls import path from .views import HeroListView, NoticficationListView urlpatterns = [ path("", HeroListView.as_view(), name="home"), path("", NoticficationListView.as_view(), name="home"), ] this is the project/urls.py file from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path("", include("heros.urls")), path("", include("products.urls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) {% extends '_base.html' %} {% block title %}Home{% endblock title %} {% block content %} {% load static %} <div class="container mt-4"> <div id="carouselExampleControls" class="carousel … -
How to use signed url to upload a file GCS using python/django (and possibly requests)
There are many examples to upload a file to Google Cloud Storage (GCS) using frontend/browser/js as below. However, I haven't seen much examples for uploading a file to GCS using python / django in the backend side. How can I modify the following code so it will use the signed url to upload a file to GCS. def Put(self, path, content_type, data): """Performs a PUT request. Args: path: The relative API path to access, e.g. '/bucket/object'. content_type: The content type to assign to the upload. data: The file data to upload to the new file. Returns: An instance of requests.Response containing the HTTP response. """ md5_digest = base64.b64encode(md5.new(data).digest()) base_url, query_params = self._MakeUrl('PUT', path, content_type, md5_digest) headers = {} headers['Content-Type'] = content_type headers['Content-Length'] = str(len(data)) headers['Content-MD5'] = md5_digest return self.session.put(base_url, params=query_params, headers=headers, data=data) -
Django app on docker. Problem with travis and logger
yestarday i added logging module to my django app. My app is running locally fine. The problem is with Travis CI. Travis is failing with building giving the error FileNotFoundError: [Errno 2] No such file or directory: '/electronic_shop/_logs/data.log': Travis building. As i understand, travis have problem with finding the _logs/data.log file. Firstly i thought adding new command to my docker file is enough (mkdir /electronic_shop/_logs), but i was wrong. So the question is, what can i do, to force travis to run my image? Docker is creating _log folder inside my image, so there should not be any error. Any ideas? Should i have to create files need for logger manually (in docker file)? Here is my docker file: FROM python:3.10-alpine EXPOSE 8000 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache postgresql-client jpeg-dev RUN apk add --update --no-cache --virtual .tmp-build-deps \ gcc libc-dev linux-headers postgresql-dev musl-dev zlib zlib-dev RUN pip install -r /requirements.txt RUN apk del .tmp-build-deps RUN mkdir /electronic_shop RUN mkdir /electronic_shop/_logs WORKDIR /electronic_shop COPY . /electronic_shop RUN mkdir -p /vol/web/media RUN mkdir -p /vol/web/static RUN adduser -u 5678 --disabled-password --gecos "" user && chown -R user /electronic_shop RUN chown -R user:user /vol/ RUN chmod … -
django.core.exceptions.ImproperlyConfigured: The included URLconf 'notes.urls' does not appear to have any patterns in it
I get this error in the root directory, not in an app. The code in urls.py of this root directory is: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('write_notes.urls')) # write_notes is the name of my app. ] What is the error and how do i fix it? -
Why is my django-crontab cronjob not executing?
I have a django-project with an app called app that has a file called cron.py with a function called main_routine(). I want the main_routine() function to be called every minute. In my django-project/django-project/settings.py I have this: INSTALLED_APPS = [ 'django_crontab', ... ] ... CRONJOBS = [ ('*/1 * * * *', 'app.cron.main_routine') ] My django-project/app/cron.py looks like this: from app.models import SomeModel from django.utils import timezone def main_routine(): object = SomeModel.objects.get(name='TestObject1') object.updated = timezone.now() object.save() Of course I ran : python3 manage.py crontab add And the terminal printed: adding cronjob: (someHash) -> ('*/1 * * * *', 'app.cron.main_routine') To be safe I run: python3 manage.py crontab show And the terminal prints: Currently active jobs in crontab: someHash -> ('*/1 * * * *', 'app.cron.main_routine') To check if evrything works I run: python3 manage.py crontab run someHash Then I take a look at the admin page and see that TestObject1 has an updatet datetime of just now. (so far everything seems to be gooing smoothly) The main issue: No matter how long I wait the job will not be executed automatically. What am I doing wrong? -
I need to convert below sql query to django orm
This my SQL query, I need to convert this to django ORM SELECT ld.post_id, min( (ld.created AT TIME ZONE c.tz)::date ) as date, count(*) as post_booked FROM marketing_post ld INNER JOIN clinics_post c ON (ld.post_id = c.id) WHERE ld.post_id IS NOT NULL -- Only look for patient leads; AND ld.type = 'P' GROUP BY ld.post_id -
How does Django rest fremakework verify the secondary password?
I'm not using auth, I've added a re_password field to my serializer, I think it only does a consistency check with the password field when a POST request comes in. But the problem is that if re_password and password are write_only, then PUT and PATCH requests must also pass in these 2 fields. I guess the consistency validation of re_password and password is reasonable for user registration, but it is not so necessary for updating user information. What can I do to make re_password and password only required for POST requests? class UserSerializer(serializers.ModelSerializer): re_password = serializers.CharField(write_only=True, min_length=6, max_length=20, error_messages={ "min_length": "Password at least 6 digits", "max_length": "Password up to 20 characters", }) class Meta: exclude = ("is_delete",) model = models.User extra_kwargs = {**CommonSerializer.extra_kwargs, **{ "password": { "write_only": True, "min_length": 6, "max_length": 20, "error_messages": { "min_length": "Password at least 6 digits", "max_length": "Password up to 20 characters", } }, }} def validate_password(self, data): return hashlib.md5(data.encode("utf-8")).hexdigest() def validate_re_password(self, data): return hashlib.md5(data.encode("utf-8")).hexdigest() def validate(self, validate_data): if validate_data['password'] != validate_data.pop('re_password'): raise exceptions.AuthenticationFailed("password not match") return validate_data def create(self, validate_data): instance = models.User.objects.create(**validate_data) return instance def update(self, instance, validate_data): password = validate_data.get("password") validate_data["password"] = hashlib.md5( password.encode("utf-8")).hexdigest() for key, val in validate_data.items(): setattr(instance, key, val) instance.save() … -
Expected view to be called with URL keyword "pk" added "pk" to urls.py
Getting the error: AssertionError at /update_profile/ Expected view UpdateProfileView to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_fieldattribute on the view correctly. when I try to update a user profile. Here is my urls.py path('update_profile/', views.UpdateProfileView.as_view(), name='update_profile'), My UpdateProfileView: class UpdateProfileView(generics.UpdateAPIView): # permission_classes = [permissions.IsAuthenticated] # authentication_classes = (TokenAuthentication,) # lookup_field = 'username' queryset = User.objects.all() serializer_class = UpdateUserSerializer @action(detail=True, methods=['put']) def perform_update(self, serializer): serializer.save(user=self.request.user.id) UpdateUserSerializer class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True) class Meta: model = User #add 'city', 'country', 'bio' fields = ['username', 'email', 'password', 'first_name', 'last_name'] def validate_email(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(email=value).exists(): raise serializers.ValidationError({"email": "This email is already in use."}) return value def validate_username(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(username=value).exists(): raise serializers.ValidationError({"username": "This username is already in use."}) return value def update(self, instance, validated_data): user = self.context['request'].user if user.pk != instance.pk: raise serializers.ValidationError({"authorize": "You don't have permission for this user."}) instance.first_name = validated_data['first_name'] instance.last_name = validated_data['last_name'] instance.email = validated_data['email'] instance.username = validated_data['username'] # instance.profile.city = validated_data['city'] # instance.profile.country = validated_data['country'] # instance.profile.bio = validated_data['bio'] instance.save() return instance I added the URL argument pk to my urls.py path('update_profile/<int:pk>', views.UpdateProfileView.as_view(), name='update_profile') This returns the error page not found at update_profile -
django messages framwork returning None when printed
I am new to django, i have stuck into an obvious issue which i cant unfold, at the form successful submission i have, put a message on the main home page where the user will be redirect to, the issue is its not returning the message.see below view: def service(request): form = GetStartedForm(request.POST or None) if form.is_valid(): form.save() x = messages.success(request, 'We have recorded your request and we will contact you soon!') print(x) print('Form Successfull!') return HttpResponseRedirect(reverse_lazy('home')) context = {'form': form} return render(request, 'bluetec/service.html', context) form: class GetStartedForm(forms.ModelForm): class Meta: model = GetStarted fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['name'].widget.attrs.update({'size': 5, 'class': 'form-control', 'placeholder': 'Enter your name:'}) self.fields['phone_no'].widget.attrs.update({'size': 5, 'title': 'Phone No', 'class': 'form-control', 'placeholder': 'Enter your phone no:'}) self.fields['email'].widget.attrs.update({'size': 10, 'title': 'Email', 'class': 'form-control', 'placeholder': 'Enter your email:'}) self.fields['description'].widget.attrs.update({'size': 10, 'title': 'description', 'class': 'form-control', 'placeholder': 'Enter your projects description:'}) and the html is <body> <div id="wrapper" > {% include 'bluetec/messages.html' %} <!-- header begin --> <header class="{% block class %} header-light transparent scroll-light {% endblock class %}"> <div class="container"> <div class="row"> the messages.html file is {% if messsages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}" id="msg" role="alert"> {{ message }} </div> … -
Cpanel - I am trying to install pillow module on my python django web.. but is not installing
domain: www.snatchupjobs.com when I remove pillow modules lines from my website then my website run perfectly but when I do not remove the pillow lines from my website then my website stops working.. it shows an error "no module name pillow". actually, my application depends on this library. the flow of my website is that users can create a CV and also users can download it; on downloading processing time I used pillow module which will convert html to png then png to pdf file... so kindly help me to solve this code here is the lines I am getting from cpanel terminal when I run this command pip install pillow.. cpanel terminal error during the module installing time -
Replace NA value with "na"
class CardRecommendation(models.Model): sign_up_bonus_special_category_spend_threshold = models.IntegerField(null=False, default=None) sign_up_bonus_special_category_spend_time_threshold = models.IntegerField(null=False, default=None) annual_fee_description = models.CharField(max_length=1024, null=False, default=None) annual_fee_amount_first_year = models.IntegerField(null=False, default=None) annual_fee_amount_second_year_onwards = models.IntegerField(null=False, default=None) purchase_intro_apr_description = models.CharField(max_length=1024, null=False, default=None)`enter code here` In this model field I am inserting data from CSV to Database. In case if I get "NA" value from CSV i have to enter "na" in database in both case either it is CharField or IntegerField. Please help how can I do this. -
How do you retrieve request.user in Django rest framework in CORS?
How do you get request.user and check if the user is authenticated or its username or so on in DRF in CORS environment? I'm new to the field of SPA, single page application. For a SPA app it's common to use DRF I heard, so I now want to utilize it to authenticate the user to return a different response. For example, simply when the user is an authenticated user w/ username then returns his username to the json response, or returns empty "" response when not his is logged-in. When it's a same-domain environment e.g. client: localhost:8000 -> api: localhost:8000/api/requested_user ; DRF can retrieve its user state well. But when it's a different domain e.g. client: localhost:8080 -> api: localhost:8000/api/requested_user ; , DRF cannot retrieve the data that checks if the user is logged-in. Example, when I have the following urls.py that handles API requests, # urls.py class RequestedUserView(APIView): permission_classes = [] def get(self, request, *args, **kwargs): return Response(data={ "is_authenticated": request.user.is_authenticated, "id": request.user.id, "username": request.user.username, }) def post(self, request, *args, **kwargs): pass urlpatterns = [ path('api/requested_user', RequestedUserView.as_view()), ] the former same-domain request (e.g. :8000 -> :8000) gives something similar to {is_authenticated: true, id: 7, username: 'ami'} when the client … -
module 'django.db.models' has no attribute 'EmbeddedField'
New to python, and getting the above error writing a simple model. I am developing on VSCode if that matters. Below are my packages, installed in venv. asgiref==3.5.0 Django==4.0.3 djongo==1.3.6 dnspython==2.2.1 Pillow==9.0.1 pymongo==4.0.2 pytz==2022.1 sqlparse==0.2.4 Just a simple model to test... from django.db import models class ItemSku(models.Model): ProductSku = models.CharField(max_length=10) class ItemsCollection(models.Model): ProductName = models.CharField(max_length=30) ProductDescription = models.CharField(max_length=300) ProductFeatures = models.CharField(max_length=300) ProductCategory = models.CharField(max_length=300) ProductCountryOfOrigin = models.CharField(max_length=30) ProductSkus = models.EmbeddedField(ItemSku) One other thing, is that I can connect to mongodb using djongo, and am able to makemigrations and migrate and view in Django admin without the 'EmbeddedField', I am just not able to create an embedded document. I hope this makes sense. Any help is greatly appreciated. -
Does prefetch or select_related help when using a model @property
I have a model like this: class Order(Model): ... @property def all_shipments_shipped(self): return all([shipment.is_shipped for shipment in self.shipments.all()]) class Shipment(Model): ... order = ForeignKey(Order, related_name='shipments', on_delete=SET_NULL, null=True) @property def is_shipped(self): return (calculate if shipped based on tracking status) and a viewset like this: @action(methods=['GET'], detail=False, url_path='num_not_shipped') def num_not_shipped(self, request): qs = self.request.user.orders.all() num_orders_not_shipped = len([i for i in qs if not i.all_shipments_shipped]) return Response(num_orders_not_shipped, status=status.HTTP_200_OK) Would adding a qs = qs.select_related('shipments') help being as that the shipment is used in the model property and not in the viewset? Thanks for the help