Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to remove members of a Team Django Python
I have teams and I have members (players). The Team owner is inviting a player to his team by email. And player is accepting invitation to join team. After acceptation they become a member of a invitated team. Now what I want to do is to make it possible for player to leave the team and also give possibility for the team owner remove player from their team. Since I am new with Django I can't achieve it yet. I've tried to create delete_member.html and function delete_member in Views first for Team owner to remove Its member but I don't see anything in that page. What Am I doing wrong? Apps: Team app - Views from django.conf import settings from django.contrib import messages from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect, get_object_or_404 from .models import Team, Invitation from .utilities import send_invitation, send_invitation_accepted @login_required def team(request, team_id): team = get_object_or_404(Team, pk=team_id, status=Team.ACTIVE, members__in=[request.user]) invitations = team.invitations.filter(status=Invitation.INVITED) return render(request, 'team/team.html', {'team': team, 'invitations': invitations}) @login_required def activate_team(request, team_id): team = get_object_or_404(Team, pk=team_id, status=Team.ACTIVE, members__in=[request.user]) userprofile = request.user.userprofile userprofile.active_team_id = team.id userprofile.save() messages.info(request, 'The team was activated') return redirect('team:team', team_id=team.id) @login_required def add(request): if request.method == 'POST': title = request.POST.get('title') if title: … -
Not getting refreshed value for Django Serializer
I have 2 models Model A Fields : a_id, a_name, common_name and Model B Fields : b_id, b_name, common_name and my Serializer is like below for Model B class ModelBSerializer: model_a_obj_list = model_a.objects.all().values(a_id a_name common_name) common_name_list = {} for model_a_obj in model_a_obj_list: common_name_list[model_a_obj['common_name']] = { a_name: model_a_obj['a_name'] a_id: model_a_obj['a_id'] } a_model_details = fields.SerializerMethodField(read_only=True) def get_a_model_details(self, instance): return self.common_name_list.get(instance.common_name) class Meta(BaseObjectSerializer.Meta): model = Model_b This Seems to be working fine for API as i am getting modela data in modelb serializer data /api for model b { b_id: bid b_name:bname common_name: cname { a_name: aname_1 a_id: aid_1 } } Problem is when i do an update on MODEL-A. and change value of parameter lets say a_name: aname_1 changed to aname_2 But this change is not reflecting in api when i am running again Can some one help me, What am i doing wrong here ?? -
Can't access object primary key after creation
I did some primary key changes in my Django project which resulted in cleaning the whole database. I tested basically the whole database and it works correctly besides one thing. When creating object and using new primary key shortly after to redirect to its page- I have an error. zam = Zamowienie.objects.create(zam_nr_zam=nr_zam) return redirect('details', zam_id=zam.zam_id) The zam_id field is my new primary key. I tried to call it by simple return redirect('details', zam_id=zam.pk) but the results are the same. Simplified model: class Zamowienie(models.Model): zam_id = models.IntegerField(unique=True, primary_key=True) zam_nr_zam = models.CharField(max_length=25, unique=True) When I try to access url of the object it works correctly (after creation) http://ip/details/1/ Exact error message: Exception Type: NoReverseMatch Exception Value: Reverse for 'details' with keyword arguments '{'zam_id': None}' not found. 1 pattern(s) tried: ['details/(?P<zam_id>[0-9]+)/$'] Any idea what my caused the issue? -
get() returned more than one Modules -- it returned 2! (REST API - Django)
I am stuck in this issue for almost 2 days. Here is the issue. My models are like this: class Modules(models.Model): module_name = models.CharField(max_length=50) module_duration = models.IntegerField() class_room = models.IntegerField() def __str__(self): return self.module_name class Students(models.Model): name = models.CharField(max_length=50) age = models.IntegerField() grade = models.IntegerField() modules = models.ManyToManyField(Modules) def __str__(self): return self.name My views are here: class StudentsViewSet(viewsets.ModelViewSet): serializer_class = StudentsSerializer def get_queryset(self): student = Students.objects.all() return student def create(self,request,*args, **kwargs): data = request.data new_student = Students.objects.create(name=data["name"], age=data['age'], grade=data["grade"]) new_student.save() for module in data["modules"]: module_obj = Modules.objects.get(module_name=module["module_name"]) new_student.modules.add(module_obj) serializer = StudentsSerializer(new_student) return Response(serializer.data) class ModulesViewSet(viewsets.ModelViewSet): serializer_class = ModudesSerializer def get_queryset(self): module = Modules.objects.all() return module ``` When I POST: { "name": "steve", "age": 16, "grade": 10, "modules": [ { "module_name": "math" }, { "module_name": "physics" } ] } It says: MultipleObjectsReturned at /app_Five/student/ get() returned more than one Modules -- it returned 2! I understand get() only get one element. But I think in "for" loop above only one "module_name" exists for each loop. So each time the get() executes, only one result for it to get. Can anyone tell me what I did wrong there? -
obfuscate Django Project
Similar questions has been already asked: How would I package and sell a Django app? But no real answer was provided previously! I have developed a Django app and to satisfy constraint of a security checklist, I have to obfuscate the project, otherwise the project will not get the necessary permits to be used by my client. I don't really care if it's a wast of time or if a determined person is eventually able to break the code. All I'm looking for is a reliable way to obfuscate the project while it's still perfectly functional. I don't mind if it can be deobfuscate after 1 second. -
Django: Unable to implement SimpleJWT
I am working on implementing Simple JWT authentication in Django. I followed the documentation and everything worked fine on my local machine. Now when I was replicating the steps on the server, an error occurred. To give a background, some migration files were deleted earlier, and makemigrations command was giving errors since dependencies were non-existent. Now I went on to this step of rotating refresh tokens, unaware of the fact that some migration files are missing, and ran the migrate command. Now after running the migrate command, Django started throwing errors, but the two token tables (token_blacklist_blacklistedtoken, token_blacklist_outstandingtoken) it creates, were created (obviously with a missing column). Now the TokenObtainPairView API started working, but I thought it can fail since we have a missing table column. So I did the following steps to revert back to the previous version. uninstalled djangorestframework-simplejwt Restored the settings.py Deleted the two token tables from DB using drop table command Now, when I'm following the documentation, I am not able to create the token table again, as the migrate command is telling me there is nothing to migrate. Generally, the applied migrations are registered in django_migrations table, but the token tables migrations were not listed … -
How do I get a visible default value for a field based on two fields, one from the same model and one from another model, in Django?
Following are my two models: class SomeThing(models.Model): name=models.ForeignKey(Name, on_delete=CASCADE) total_fee=models.DecimalField(max_digits=7, decimal_places=2, default=0) class AnyThing(models.Model): name=models.ForeignKey(Name, on_delete=CASCADE) discount=models.DecimalField(max_digits=5, decimal_places=2, default=0) net_fee=models.DecimalField(max_digits=7, decimal_places=2, default="Something.total_fee-discount") I want the net fee to be visible to the user in real time as he is filling up the form. The field must calculate the net fee by subtracting discount in the same model from the total fee in the previous one. Is there any Django-way for achieving it? -
how to use filter in query twice in django
I am trying to filter some data using this query, get_members = PaymentDetails.objects.filter(participants_name=Participants.objects.filter(participants_name=Profile.objects.get(user=request.user))) but I am getting this error The QuerySet value for an exact lookup must be limited to one result using slicing. My models looks like this class Committee(models.Model): committee_creator = models.ForeignKey(Profile, on_delete=models.CASCADE) committee_name = models.CharField(max_length=100) class Participants(models.Model): participants_name = models.ForeignKey(Profile, on_delete=models.CASCADE) participants_committee_name = models.ForeignKey(Committee, on_delete=models.CASCADE) class PaymentDetails(models.Model): participants_name = models.ForeignKey(Participants, on_delete=models.CASCADE) participants_paid_status = models.BooleanField(default=False) participants_amount_paid = models.IntegerField() -
Django dynamic formset with Jquery Ui autocomplete
Hi there I am fairly new to django and need to add dynamic formsets with autocomplete functions for every from. I am not entirely sure what I am doing wrong i have tried a few approaches and this is my most recent! I have function called AutoproductComplete which receives the id of the current formset form input that i want to add the auto complete to. It doesnt work, no errors, not sure why. I also did it after the after method so assume the form has been added to the DOM?' 'html' <form class="form-horizontal" method="POST" action=""> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div class="row form-row spacer"> <div class="input-group" style="padding:5px;"> {{form.productName}} {{form.orderQuantity}} <div class="input-group-append"> <button class="btn btn-success add-form-row" style="margin:5px;">+</button> </div> </div> </div> {% endfor %} <br> <div class="row spacer"> <div class="col-12 offset-9"> <button type="submit" class="btn btn-block btn- dark">Create Order</button> </div> </div> </form> JavaScript ''' function AutoproductComplete(id){ const products = []; console.log("This is working") console.log(id) {% for instance in products %} products.push("{{instance.product_name}}") {% endfor %} $(id).autocomplete({ classes: {"ui-autocomplete-input": "highlight"}, source: products, minLength: 1, }); }; AutoproductComplete("id_form-0-productName" ) function cloneMore(selector, prefix) { var newElement = $(selector).clone(true); var id = "" var total = $('#id_' + prefix … -
Django templates _set.all two sub table
I have two tables I want to check if there is data or not! {% if user.children_set.all.groups_set.all.exists %} -
How do you handle a PATCH request from HTMX in Django?
I would like to send a PATCH request to my app but I'm not sure how to consume the request in Django. I am currently getting the following error. AttributeError: 'WSGIRequest' object has no attribute 'PATCH' The input field in the HTMX file looks like this (I also made sure to send the CSRF token): <input hx-patch="{% url 'my_update' myobj.id %}" hx-swap="none" /> This is the Django View class MyHtmxView(View): def patch(self, request, *args, **kwargs): form = MyForm(request.PATCH) if form.is_valid(): form.save() # return an okay status? 200? else: return HttpResponse(self.form_invalid(form)) Django is receiving the request, but isn't sure what to do with request.PATCH. I can see in the Django docs that there is a HttpRequest.GET and HttpRequest.POST but no HttpRequest.PATCH https://docs.djangoproject.com/en/3.2/ref/request-response/#httprequest-objects. What's the best way to handle the PATCH? -
How to display products in child loop related to products in main loop with django?
The main loop displays product Card (B, C, D...) related by brand (or category) of product A. In product card B, C, D... That is, a sub-loop, showing up to 3 products with the same (exact) model as product B, C, D... Is there a way to do that for the DetailView. I also want to apply that to the tags on the category page (ListView). With the code in the parent loop it works fine, however the code in the child loop it doesn't work properly. My codes are as below (code has been shortened): Models.py class Modelp(models.Model): name=models.CharField(max_length=100, blank=True, null=True,) slug = AutoSlugField(max_length=100, populate_from='name') class Meta: verbose_name_plural='Models' def __str__(self): return self.name class Product(models.Model): title = models.CharField( verbose_name=_("title"), help_text=_("Required"), max_length=200 ) slug = models.SlugField(max_length=200, unique=True) modelp=models.ForeignKey(Modelp, blank=True, null=True, on_delete=models.CASCADE) category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.RESTRICT) brand = models.ForeignKey(Brand, blank=True, null=True, on_delete=models.CASCADE) store = models.ForeignKey(Store, null=True, blank=True, on_delete=models.CASCADE) popularity = models.IntegerField(verbose_name=_("Popularity"), default=0) class Meta: verbose_name = _("Product") verbose_name_plural = _("Products") def __str__(self): return self.title def get_absolute_url(self): return reverse('product-detail', kwargs={'slug': self.slug}) views.py class ProductDetailView(DetailView): template_name = 'product_detail.html' model = Product def get_template_names(self): if self.request.htmx: return 'product/all_variations.html' return 'product_detail.html' def get_context_data(self, **kwargs): context = super(ProductDetailView, self).get_context_data(**kwargs) context_related_brand = Product.objects.filter(brand=self.object.brand).exclude( slug=self.kwargs['slug'])[:6] context_related_modelp = … -
Acess context from request in Django
How can we access the context passed in template in method views? def method_A(request): context = {"name":"sample"} html_template = loader.get_template('some_template.html') return HttpResponse(html_template.render(context, request)) Template as <div> {{name}} <a href="method_B">Redirect</a> </div> def method_B(request): # Here how to get context which was present earlier context = {"second":"second"} html_template = loader.get_template('template_B.html') return HttpResponse(html_template.render(context, request)) How we can get context in method based views in django.? So that it can be used in another templates. -
Django API split data by unique ID
I am making Django API. I collected place and review data using crwaling program. I want to split review data by building name(unique key), but it seems all reviews are saved together and is spread to all URL. models.py from django.db import models import uuid # Create your models here. from django.utils.text import slugify def generate_unique_slug(klass, field): origin_slug = slugify(field, allow_unicode=True) unique_slug = origin_slug numb = 1 while klass.objects.filter(slug=unique_slug).exists(): unique_slug = '%s-%d' % (origin_slug, numb) numb += 1 return unique_slug class BuildingData(models.Model): building_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=50, unique=True, allow_unicode=True, default=uuid.uuid1) building_loc = models.CharField(max_length=50) building_call = models.CharField(max_length=20) #building_time = models.CharField(max_length=50) def save(self, *args, **kwargs): if self.slug: # edit if slugify(self.building_name, allow_unicode=True) != self.slug: self.slug = generate_unique_slug(BuildingData, self.building_name) else: # create self.slug = generate_unique_slug(BuildingData, self.building_name) super(BuildingData, self).save(*args, **kwargs) class ReviewData(models.Model): building_name = models.CharField(max_length=50) review_content = models.TextField() star_num = models.FloatField() urls.py from django.contrib import admin from django.urls import path from crawling_data.views import ReviewListAPI from crawling_data.views import BuildingInfoAPI urlpatterns = [ path('admin/', admin.site.urls), path('api/buildingdata/', BuildingInfoAPI.as_view()), path('api/buildingdata/<str:slug>/', ReviewListAPI.as_view()) ] A part of crwaling program if __name__=='__main__': for item in building_dict: BuildingData(building_name = item['place'], building_loc = item['location'], building_call = item['call']).save() #BuildingData(building_name = item['place'], building_loc = item['location'], building_call = item['call'], building_time = item['time']).save() for item … -
Django filters custom date format for DateFilter
Can we customize date format for DateFiler in django_filters. Right now DateFilter accepts yyyy-mm-dd. Can we change it to mm-dd-yyyy? -
How to reference a serializer in Djano
I have two serializers for both Product and Ingredient models, I want to use both relations in the frontend side. As products in Ingredient model (ingredient.products) and I want the same in Product model (product.ingredients), so how can I get it? This is my code, class IngredientSerializer(serializers.ModelSerializer): # products = serializers.SerializerMethodField() //this line doesn't work class Meta: model = Ingredient fields = '__all__' class ProductSerializer(serializers.ModelSerializer): ingredients = IngredientSerializer(many=True, required=False) class Meta: model = Product fields = '__all__' And the Ingredient modal, class Ingredient(models.Model): products = models.ManyToManyField('Product', related_name="ingredients", null=True) name = models.CharField(max_length=100, blank=True, null=True) image = models.ImageField(blank=True, null=True) -
Django session is not creating in browser of computer Seems like antivirus blocking to create session session is creating if turn off antivirus [closed]
Django session is not creating in the browser seems like session creation is blocking by antivirus .(Session is working fine with non protected Browser) What may be the route cause of the issue . do we need to follow any standard to create session with out any blockage by antivirus ? -
Filter distinct objects from ManyToMany within ManyToMany
I have following Models in my Django DRF app. class FilterValue(models.Model): code = models.Charfield(…) class ProductVariant(models.Model): filters = models.ManyToManyField("FilterValue", blank=True, …) class Product(models.Model): variants = models.ManyToManyField("ProductVariant", blank=True, …) category = models.ForeignKey("Category", blank=True) And I’m trying to define function on Category model which will return all objects of FilterValue attached to all ProductVariants of all Products that are assigned in the category. Since I’ll have loads of different ProductVarints I can’t get away with nested loops since it’d be really slow. I had multiple attempts to solve it. I can of course get all Products within a Category using: products = Product.objects.filter(category=self) But then I get stuck on the fact that I actually need to filter nested ManyToMany object since I need all ProductVariants of all Products in the QuerySet and then - in the another level I need all ManyToMany FilterValue objects of each ProductVariant. Thank you. -
Create model instance only if its user id field is equal to the logged-in user's id
In a django rest framework app, there's a TextViewSet. The Text object structure is as follows: { text: text_value, author: author_id } When creating a new Text instance, I want to check if the supplied author_id equals the currently logged-in user's id. I've read this question: When to use Serializer's create() and ModelViewset's perform_create(), but still can't decide whether to override Serializer's create(), ModelViewset's create() or perform_create() methods. What's the right method to override? -
How to automatically check if the subscription of the user has expired and to make changes in the model?
I am making a website, where the user chooses a plan that have diferrent durations such as 7days, 14days, 21days. However the plan does not get activated immediately. After the user completes the registation process he has to accept an agreement, and then depending on the type of plan he has choosen the expiration date is set from the date of acceptance, and a field contract_status is set True. Now, I want to know how I can automatically check that the expiration date of a user has reached and set the contract_status of that user to false and then perhaps do some other stuff. But mainly I want to know how I can check subscription expiration automatically to set the field to False. models.py This is the model that has the fields to store the that date of acceptance, expiration and contract status class Contract(models.Model): user = models.OneToOneField(CustomUser, null= True, on_delete=models.CASCADE) contract_status = models.BooleanField(default=False) date_of_acceptance = models.DateTimeField(null= True) date_of_expiration = models.DateTimeField(null=True, blank=True) views.py This is the view that deals with the above model when the user accpets the agreement if request.method == 'POST': agreement = Contract() if request.user.plan == '7days': agreement.user = request.user agreement.contract_status = True expiry = datetime.now() + … -
Static File On Django 3.2 Not Loading
My Problem is quite simple and yet I'm finding it so hard to solve it. The problem is I am not able to load the CSS File and image which are on the static folder located on the root folder of the project. The static folder is not under the app name. My project name is "ecommerce" and my app name is "store". This is my file hierarchy for my project. This is my settings.py I have added my app too. Yes, the STATICFILES_DIRS too. Tried the other one too. STATICFILES_DIRS = [ BASE_DIR / "static", ] I used temp.html for showing the demo and here is my code. And the CSS file which is named main.css After doing all the things properly, the CSS file and image won't load. Errors That I got in my terminal And in developer mode in Chrome As I know this is quite a rookie mistake and I am a beginner. I can't continue forward till this problem is solved. I'd be grateful if someone could come forward and assist me in resolving the issue. -
please explain me what super().save() is exactly doing here (please dont mark it as duplicate question other answers are hard to understand)
please explain me what super().save() is exactly doing here (please dont mark it as duplicate question other answers are hard to understand). Try to keep it easy to understand. I will be very greatfull. Thanks def save(self, *args, **kwargs): original_slug = slugify(self.title) queryset = BlogPost.objects.all().filter(slug__iexact=original_slug).count() count = 1 slug = original_slug while(queryset): slug = original_slug + '-' + str(count) count += 1 queryset = BlogPost.objects.all().filter(slug__iexactf=slug).count() self.slug = slug if self.featured: try: temp = BlogPost.objects.get(featured=True) if self != temp: temp.featured = False temp.save() except BlogPost.DoesNotExist: pass super(BlogPost, self).save(*args, **kwargs) This is the first time i am trying to learn about super().save() and i am finding it difficut to understand from from other answers on stackoverflow -
django-query: get parent value based on children field
I am sorry if I am not very clear with the query I am trying to build, based on the following models: class BankingDetail(models.Model): sfAttachmentID = models.CharField(max_length=18, unique = True) created = models.DateTimeField(auto_now_add=True) class TransactionBankDetail(models.Model): bankingDetail = models.ForeignKey(BankingDetail, on_delete=models.CASCADE, related_name='BankingDetails') institution = models.TextField(blank=True, unique = False, null=True) I am trying to find which institutions I have and how many are they. However, because 1 BankingDetail can have multiple TransactionBankDetail, I want to count this values only once. In other words, based in my query: #institution_by_attachments = TransactionBankDetail.objects.filter(institution__isnull=False).values('bankingDetail__sfAttachmentID', 'institution').annotate(total=1).order_by('total').reverse() institution_by_attachments = TransactionBankDetail.objects.filter(institution__isnull=False).values('bankingDetail__sfAttachmentID', 'institution') for i in institution_by_attachments: print(i) my result will look like {'bankingDetail__sfAttachmentID': '0067F0000bCRuSx', 'institution': 'Atlantic'} {'bankingDetail__sfAttachmentID': '0067F0000bCRuSx', 'institution': 'Atlantic'} {'bankingDetail__sfAttachmentID': '0067F0000bCRuSx', 'institution': 'Atlantic'} {'bankingDetail__sfAttachmentID': '0067F0000bCRuSx', 'institution': 'Atlantic'} {'bankingDetail__sfAttachmentID': 'Ost89Porque-111', 'institution': 'Atlantic'} {'bankingDetail__sfAttachmentID': '0060p000008ieSm', 'institution': 'South Pacific'} {'bankingDetail__sfAttachmentID': '0060p000008ieSm', 'institution': 'South Pacific'} {'bankingDetail__sfAttachmentID': '0060p000008ieSm', 'institution': 'South Pacific'} {'bankingDetail__sfAttachmentID': '0060p000008ieSm', 'institution': 'South Pacific'} {'bankingDetail__sfAttachmentID': '0060p000008ieSm', 'institution': 'South Pacific'} {'bankingDetail__sfAttachmentID': '0060p000008lpYC', 'institution': 'Africa'} {'bankingDetail__sfAttachmentID': '0060p000008lpYC', 'institution': 'Africa'} {'bankingDetail__sfAttachmentID': '0060p000008lpYC', 'institution': 'Africa'} {'bankingDetail__sfAttachmentID': '12365478987test123', 'institution': 'South Pacific'} {'bankingDetail__sfAttachmentID': '12365478987test123', 'institution': 'South Pacific'} {'bankingDetail__sfAttachmentID': '12365478987test123', 'institution': 'South Pacific'} If i use this for my aggregate I will be getting the wrong results: Atlantic 5 South Pacific 8 Africa 3 What I want is: South … -
how to pass the total amount of product to payment gateway
i'm building an ecommerce site with django. once the user press checkout, there is an html billing form which popsup and prompts the user to enter address, email etc. i also passed data like email and it worked fine. but when i try for the amount it doesnt pass how would i pass the amount to the Payment gateway? the Html form <form> <div class="container-fluid"> <div class="row no-gutter"> <div class="col-md-12"> <div class="login d-flex align-items-center py-5"> <div class="container"> <div class="row"> <div id="payment-form" class="col-12 col-lg-6 mx-auto"> <h3 class="mb-3">Billing address</h3> <!-- Error messages in this element --> <div class="row g-3"> <div class="col-sm-7"> <label for="firstName" class="form-label">Full Name</label> <input type="text" class="form-control" id="fullName" placeholder="" required> <div class="invalid-feedback"> Valid first name is required. </div> </div> <div class="col-12"> <label for="email" class="form-label">Email <span class="text-muted">(Optional)</span></label> <input type="email" class="form-control" id="email" placeholder="you@example.com"> <div class="invalid-feedback"> Please enter a valid email address for shipping updates. </div> </div> <div class="col-12"> <label for="address" class="form-label">Address</label> <input type="text" class="form-control" id="custAdd" placeholder="1234 Main St" required> <div class="invalid-feedback"> Please enter your shipping address. </div> </div> <div class="col-12"> <label for="address2" class="form-label">Address 2 <span class="text-muted">(Optional)</span></label> <input type="text" class="form-control" id="custAdd2" placeholder="Apartment or suite"> </div> <div class="col-md-5"> <label for="country" class="form-label">Country</label> <select class="form-select" id="country" required> <option value="">Choose...</option> <option>United States</option> </select> <div class="invalid-feedback"> Please select a … -
Django database access speed depends on host used in request
I am having performance/speed issues in a Python/Django/Postgres application. Specifically, the speed of database queries (via Django's ORM) appears to be related to the hostname used in the request to django. The examples I'm using use either localhost or the VM's hostname (dev.virtual). Using the hostname, performance is good, but using localhost there is a significant slowdown (in the order of tens of times slower). I've created a very basic view to test this: def generate_load_view(request, resource): length = int(request.GET.get("length")) length = 2 ** length iterations = int(request.GET.get("iterations")) iterations = 10 ** iterations if resource == "compute": load_generator = generate_compute_load elif resource == "memory": load_generator = generate_memory_load elif resource == "database": load_generator = generate_database_load else: raise Http404() t_start = time.monotonic() load_generator(length=length, iterations=iterations) t_end = time.monotonic() t_elapsed = t_end - t_start response = {"time": t_elapsed} return Response(response) def generate_database_load(length, iterations): model = django.contrib.contenttypes.models.ContentType pks = model.objects.values_list("pk", flat=True) for _ in range(iterations): random_pk = random.choice(pks) random_obj = model.objects.get(pk=random_pk) I'm using django's ContentType object out of convenience. The database (PostgreSQL) is running in a docker container on the same machine. I've used both django's development server (via manage.py) and a gunicorn server with no appreciable change. To reiterate, if I make a request …