Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter list with Remaining days of date of birth in Django
I want to display an upcoming birthday list with the remaining days of 30 days. Example: Name Date Of Birth Remaining Days John Die 2050-10-25 4 Days Left John Snow 2050-10-26 5 Days Left I dont know how to calculate remaining days but i try this code but i got error "can't subtract offset-naive and offset-aware datetimes" customer=Customer.objects.filter()[:10] for i in customer: remaining = i.dateOfBirth - datetime.today() print(remaining) -
Django JQuery Autocomplete for two forms on one page
Found this autocomplete code on the web, but it works for one form on the page. How to make it work for two forms with different data for each one? views.py from django.http import JsonResponse from django.shortcuts import render # Create your views here. from core.models import Product def autocomplete(request): if 'term' in request.GET: qs = Product.objects.filter(title__icontains=request.GET.get('term')) titles = list() for product in qs: titles.append(product.title) return JsonResponse(titles, safe=False) return render(request, 'core/home.html') models.py class Product(models.Model): title = models.CharField(max_length=124) qty = models.IntegerField() def __str__(self): return self.title home.html <form> <label for="product">Product</label> <input type="text" name="product" id="product"> </form> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(function () { $("#product").autocomplete({ source: '{% url 'autocomplete' %}', minLength: 2 }); }); </script> urls.py urlpatterns = [ path('', views.autocomplete, name='autocomplete'), ] -
django Create lazy queryset method
I want to create lazy method in QuerySet class: I want from this method to make extra filtering accordings to fileds in the querysets: class CustomQuerySet(Queryset): def extra_filter(self): fields = self._fields: lookup =getattr(self._query,"_lookup_joins",[]) #processing and return the custom queryset when I user the extra_filter before django filter then the the values of fields and lookups is empty. MyModel.objecs.extra_filter().filter(....) # doesn't workd the values of "fields" and "lookup" is empty MyModel.objects.filter(...).extra_filter() # it work So, how to extra_filter lazy to excute in all cases? -
Docker : Alpine : Django - Error installing python mysqlclient library
I am building an Alpine based image of a Django application to connect with a MySQL db. For connecting with the database, I am using mysqlclient. For building the image, I am using docker-compose. When I do docker-compose build I get the respective error: #15 7.366 Downloading mysqlclient-1.3.0.tar.gz (76 kB) #15 7.403 Preparing metadata (setup.py): started #15 7.545 Preparing metadata (setup.py): finished with status 'error' #15 7.545 ERROR: Command errored out with exit status 1: #15 7.545 command: /usr/local/bin/python -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-3fyj3dl9/mysqlclient_4a600f29b1334b47a39251a3f24d8315/setup.py'"'"'; __file__='"'"'/tmp/pip-install-3fyj3dl9/mysqlclient_4a600f29b1334b47a39251a3f24d8315/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-wh30qihi #15 7.545 cwd: /tmp/pip-install-3fyj3dl9/mysqlclient_4a600f29b1334b47a39251a3f24d8315/ #15 7.545 Complete output (10 lines): #15 7.545 /bin/sh: mysql_config: not found #15 7.545 Traceback (most recent call last): #15 7.545 File "<string>", line 1, in <module> #15 7.545 File "/tmp/pip-install-3fyj3dl9/mysqlclient_4a600f29b1334b47a39251a3f24d8315/setup.py", line 17, in <module> #15 7.545 metadata, options = get_config() #15 7.545 File "/tmp/pip-install-3fyj3dl9/mysqlclient_4a600f29b1334b47a39251a3f24d8315/setup_posix.py", line 47, in get_config #15 7.545 libs = mysql_config("libs_r") #15 7.545 File "/tmp/pip-install-3fyj3dl9/mysqlclient_4a600f29b1334b47a39251a3f24d8315/setup_posix.py", line 29, in mysql_config #15 7.545 raise EnvironmentError("%s not found" % (mysql_config.path,)) #15 7.545 OSError: mysql_config not found #15 7.545 ---------------------------------------- #15 7.545 WARNING: Discarding https://files.pythonhosted.org/packages/6a/91/bdfe808fb5dc99a5f65833b370818161b77ef6d1e19b488e4c146ab615aa/mysqlclient-1.3.0.tar.gz#sha256=06eb5664e3738b283ea2262ee60ed83192e898f019cc7ff251f4d05a564ab3b7 (from https://pypi.org/simple/mysqlclient/). … -
Django - Passing a json or an array in URL for an API call
I want to pass a number off variables (either as a JSON or Array) via an API, such as: {'age': 35, 'gender':'female', ...etc} I am not sure how to pass this information into the Djano URL. I could set up individual parameters in the URL, but I got quite a few to pass. there must be an easier way of doing it -
Django app on Heroku doesnt store users created wth admin panel
I have Django app deployed on Heroku. While building the app I have created only 2 superusers. After deployment on Heroku I can login to admin panel and I can create users, but they are not stored permanently. I see them created and I see them saved. If I log off and login again I can see them. But, after a while, they are removed. If I change the email of the 2nd superuser, It will be changed and saved, but also, after a while, this change is reversed or deleted. I am not sure if this make any sense and I am not sure if this is Django, Heroku or SQLite bug/feature. Any help would be much appreciated. Since I didn`t find similar issue, it is very interesting to me if this is something new or well known issue. -
Django - Remove duplicate from the API end point
I have designed a microservices where I'm getting the JSON from the end point and I'm able to display it in the API but I'm getting the repeated data again and again for each id. im getting json data from localhost:8000 and i want to display it with current localhost:7000.I have done some wrong but couldn't able to find where Im going wrong.I'm stuck here views.py class filterlistView(APIView): def get(self, request): filter_list = Userbase.objects.all() # serializer = UserSerializer(filter_list, many=True) # return Response(serializer.data) return Response([self.formatfilter(filter) for filter in filter_list]) def formatfilter(self, post): table_data= requests.get('http://127.0.0.1:1500/api/').json() # return render(request, 'home.html',{'table_data':table_data}) return { 'id':post.id, 'Payment_Term':post.Payment_Term, 'Netdue_Date':post.Netdue_Date, 'Predicted_Paid_days':post.Predicted_Paid_days, 'PBK_Desc':post.PBK_Desc, 'Vendor_Name':post.Vendor_Name, 'Reference':post.Reference, 'company_code':post.company_code, 'Area':post.Area, 'country':post.country, 'table_data':table_data, } output: { "id": 1, "Payment_Term": "demo2", "Netdue_Date": "2021-10-20", "Predicted_Paid_days": "2021-10-20", "PBK_Desc": "sf", "Vendor_Name": "AB", "Reference": "AB", "company_code": "1074", "Area": "GCR", "country": "CEE", "table_data": [ { "id": 1, "stage": "Stage3 Train/Stage4 Test", "region": "NORTH AMERICA", "area": "US", "country": "US", "VendorName": "FOXLINK INTERNATIONAL INC", "PBK_Desc": "Free for payment" }, { "id": 2, "stage": "Stage3 Train/Stage4 Test", "region": "NORTH AMERICA", "area": "US", "country": "US", "VendorName": "FOXLINK INTERNATIONAL INC", "PBK_Desc": "Free for payment" }, ] }, { "id": 2, "Payment_Term": "3434", "Netdue_Date": "2021-10-20", "Predicted_Paid_days": "34", "PBK_Desc": "sfsd", "Vendor_Name": "fdsdf", "Reference": "sdfsd", "company_code": "1154", … -
Deloying Django app Apach2: 403 Forbidden error. Permission denied: mod_wsgi
I am trying to deploy my Django app with my Digital Ocean droplet. There was a very useful YouTube tutorial that I followed; when he adjusted settings in Apache2, and then refreshes, he sees his Django app, whereas when I do the same, I get the following error: Forbidden You don't have permission to access this resource. Apache/2.4.46 (Ubuntu) Server at 159.223.6.157 Port 80 Here you see the setup of my /etc/apache2/sites-available/hbm_project.conf file: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn … -
will my postgresql trigger execute even if I set the value from django model at save?
I have created a trigger on each row INSERT/UPDATE to set the created_at and updated_at respectively. Trigger: CREATE OR REPLACE FUNCTION insert_update_function() RETURNS trigger AS $BODY$ BEGIN -- CHECKING OPERATION TYPE AND DECIDE COLUMN IF TG_OP = 'INSERT' THEN NEW.created_at := current_timestamp; ELSE NEW.updated_at := current_timestamp; END IF; RETURN NEW; END; $BODY$ LANGUAGE plpgsql VOLATILE; Apply Trigger only those table where updated_at column exists DO $$ DECLARE t text; BEGIN FOR t IN SELECT table_name FROM information_schema.columns WHERE column_name = 'updated_at' LOOP EXECUTE format('CREATE TRIGGER insert_update_trigger BEFORE INSERT OR UPDATE ON %I FOR EACH ROW EXECUTE PROCEDURE insert_update_function()', t,t); END loop; END; $$ language plpgsql; So when I do INSERT/UPDATE from raw SQL I don't provide these two columns i.e created_at and updated_at, it is automatically trigged and added on my table which is expected and fine but now my query is when I try to INSERT/UPDATE row's of the table through the Django BaseModel where I am setting created_at and updated_at, the trigger will be again called? Django BaseModel with custom save() class AutoCreatedField(models.DateTimeField): """ A DateTimeField that automatically populates itself at object creation. By default, sets editable=False, default=datetime.now. """ def __init__(self, *args, **kwargs): kwargs.setdefault('editable', False) kwargs.setdefault('default', now) super().__init__(*args, … -
Nested annotation in Django View and serializers
I have a use case where I wanted to have data in the below format. { "total_discount_amount": 0, "total_paid": 0, "total_billed": 0, "visits": "string" "users_summary": [ { "id": "string", "date": "string", "total_discount_amount": 0, "total_paid": 0, "total_billed": 0, "visits": "string" } ] } The outer part of the data is the sum of users_summary list data. class Test(generics.ListAPIView): queryset = Model.objects.all() serializer_class = SummarySerializer def list(self, request, *args, **kwargs): data =Model.objects.values('user').annotate(visits=Count('user'),total_discount_amount=Sum('model__amount', total_paid = Sum('model__paid_amnt',total_billed = Sum('model__bill_amnt').filter() return data Here I am not getting the outer values. I tried to implement the serializer in a way that I can get users_summary aggregated data however couldn't achieve it. Any solution to it? -
'NoneType' object has no attribute 'add' (Django nested serializer)
I'm trying to update object but if main_photos_data.get('id', None): MainPhoto.objects.filter(id=main_photos_data.get( 'id')).update(**main_photos_data) else: id = instance.id project = Project.objects.get(id=id) new_main_photo = MainPhoto.objects.create(**main_photos_data) *project.main_photo.add(new_main_photo)* error in this line getting this error: File "/home/askar/work/tasnif-backend/portfolio/serializers.py", line 143, in update project.main_photo.add(new_main_photo) AttributeError: 'NoneType' object has no attribute 'add' I've tried: project.main_photo = new_main_photo But got this error: TypeError at /portfolio/edit-project/1/ Direct assignment to the forward side of a many-to-many set is prohibited. Use photo.set() instead. -
get the user email after deletation django
I was working with the settings.AUTH_USER_MODEL and I want the email of the user to remain( after the user deleted). the user is a foreign key in my model. here is the code class Text(models.Model): title = models.CharField(max_length=45) text = models.TextField() user= models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET(??) ) # TODO : should change( remain email from the deleted user) thanks for your help -
While working with django I am seeing warnings [duplicate]
This is the warning I get when I run and Django commands in the console. WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages) -
how to remove instruction labels in django-registration-redux registration form
I followed Django-registration-redux start guide and everything works fine but the registration form shows instruction label for username and password which is like in the picture below. I don't want it so how can I remove it? -
Django Search functionality: form returns None
i am trying to build a django search functionality for my app but the input form keeps returning a none views.py def search(request): if request.method == 'POST': query = request.POST.get('text') houses = Product.objects.filter(name__contains='query') context = { 'houses':houses, } return render (request, 'searchresult.html',context ) search.html <form> <input type='text' placeholder='search houses> <button type='submit'>Search</button> </form> -
how to write testcase of not adding a same number in 2 factor auth in django
how to write this testcase in correct way i have tried a lot times but it is failedmany times def test_same_number_add(self): device = self.user.totpdevice_set.create(name='default', key=random_hex()) response = self._post({'phone_setup-current_step': 'setup', 'setup-number': '+918362758326', 'setup-method': 'sms'}) print(response.content) self.assertContains(response, 'Token:',status_code=200) p = PhoneDevice(number="+918770109512", user=self.user) p.save() response = self._post({'token-otp_token': totp(device.bin_key), 'phone_setup-current_step': 'token'}) response = self._post({'phone_setup-current_step': 'setup', 'setup-number': '+918274610917', 'setup-method': 'sms'}) #print(response.status_code) print(response.content) self.assertContains(response, 'Same number cannot be added twice',status_code=200) -
How do you prefill a value in a model form field using __init__ in django?
So basically I want to be able to prefill a Charfield form field with a certain value in the init method. Here is my form: class UpdateForm(forms.ModelForm): #_____________________________________________________________ def __init__(self, *args, **kwargs): super(UpdateForm, self).__init__(*args, **kwargs) self.fields['form_field'].initial = "How are you doing?" self.fields['form_field'].widget = self.fields['form_field'].hidden_widget() #_____________________________________________________________ class Meta: model = form_model fields = ( 'form_field', ) However, I cannot seem to set the value of my form_field with How are you doing?. Morever, I need to be able to change the value in the init method. Does anyone know how I can do this? Thank you, and please send me any questions you have. -
unable to load photos in Django after deploying to heroku
I have made a portfolio + blog website using Django. it works perfectly when running it locally but after I deployed it to Heroku, accessing the portfolio redirected me to a 500 server error. I turned on debug mode and when I did the same, it didn't throw a 500 server error, however, the pictures won't load. this is very confusing and help will be very appreciated... settings.py from pathlib import Path import os from dotenv import load_dotenv load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'projects', 'blog', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'personal_portofolio.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ["personal_portofolio/templates/"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'personal_portofolio.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': … -
Is exact querying of ArrayField possible?
Documentation on ArrayField only has contains. I know you can use __n__iexact on the ArrayField to get an exact match of n position... Apart from chaining a bunch of __n__iexact, is there a better way? More specifically to my use case, I'm using django-filters and I want to be able to exactly search for an object by its slug ArrayField. -
Can i use email verification function and Login With google in one project. (in django)
I try to make a website that have email verification and login with google function, so first i make email verification function, and it work and then i try to make login with google function but when I see in the tutorial, there can only be 1 function, namely choosing a verification email or logging in with google, because the verification email section I made with a custom auth system, while logging in with google in the tutorial uses the default auth system from a package. If you can use both, how? -
Is it possible to add a data to nested just using UUID of it?
I'm quite new to DRF and I trying to build a system with Document and Category. These are models.py for it class TimeStampedModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class Document(TimeStampedModel): unique_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) title = models.CharField(max_length=50, blank=True, default="") description = models.TextField(blank=True, default="") image = models.ImageField(blank=True, null=True) category = models.ForeignKey( 'Category', on_delete=models.SET_NULL, related_name='documents', blank=True, null=True, ) class Meta: ordering = ("-created_at",) class Category(TimeStampedModel): unique_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=50, blank=True, default="") description = models.TextField(blank=True, default="") class Meta: ordering = ("-created_at",) def __str__(self): return self.name And Serializes.py class DocumentViewSet(ModelViewSet): serializer_class = DocumentSerializer queryset = Document.objects.all() lookup_field = "unique_id" @action(detail=True, methods=['delete']) def delete_document(self, request, unique_id): """Delete document""" docs = Document.objects.get(unique_id=unique_id) try: docs.delete() return Response(status=status.HTTP_204_NO_CONTENT, data={'message': f'Delete successfully with {docs.unique_id}'}) except: return Response(data={'message': f'Delete failed with {docs.unique_id}'}) class CategoryViewSet(ModelViewSet): serializer_class = CategorySerializer queryset = Category.objects.all() lookup_field = "unique_id" filterset_fields = "__all__" @action(detail=True, methods=['delete']) def delete_category(self, request, unique_id): """Delete category""" cats = Category.objects.get(unique_id=unique_id) try: cats.delete() return Response(status=status.HTTP_204_NO_CONTENT, data={'message': f'Delete successfully with {cats.name}'}) except cats.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND, data={'message': f'Delete failed with {cats.name}'}) What I'm trying to do is update the Category name, description and add the Document to Category using UUID of Document with these JSON … -
How to return a list of available time slots via a forms ValidationError
models.py from django.db import models from django.utils import timezone from django.urls import reverse from django.contrib.auth.models import User class Customer(models.Model): username = models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=20,null=True) def __str__(self): return self.name # Create your models here. class Booking(models.Model): customer_name = models.ForeignKey(Customer,on_delete=models.CASCADE,null=True) username = models.ForeignKey(User,on_delete=models.CASCADE) qty_plts = models.PositiveSmallIntegerField(default=1) cbm = models.PositiveSmallIntegerField(default=1) created_date = models.DateTimeField(default=timezone.now()) delivery_date = models.DateField(null=True) delivery_time = models.TimeField(null=True) booking_number = models.CharField(max_length=50,unique=True) def __str__(self): return self.booking_number def save(self, **kwargs): if not self.booking_number: self.booking_number = f"{self.delivery_date:%Y%m%d}{self.delivery_time:%H%M}" super().save(**kwargs) def get_absolute_url(self): return reverse('bookmyslot:detail',kwargs={'pk':self.pk}) forms.py from django import forms from bookmyslot.models import Booking,Customer from bootstrap_datepicker_plus import DatePickerInput import datetime as dt from django.utils import timezone HOUR_CHOICES = [(dt.time(hour=x), '{:02d}:00'.format(x)) for x in range(7, 13)] class BookingForm(forms.ModelForm): def __init__(self,*args,**kwargs): user = kwargs.pop('username',None) super(BookingForm,self).__init__(*args,**kwargs) self.fields['qty_plts'].label = "Quantity Of Pallets" self.fields['cbm'].label = "Shipment CBM" self.fields['delivery_date'].label = "Delivery Date" self.fields['delivery_time'].label = "Delivery Time" self.fields['customer_name'].label = "Customer Name" self.fields['customer_name'].queryset = Customer.objects.filter(username=user) def clean(self): cleaned_data = super(BookingForm,self).clean() booking_number = f"{cleaned_data.get('delivery_date'):%Y%m%d}{cleaned_data.get('delivery_time'):%H%M}" if Booking.objects.filter(booking_number=booking_number).exists(): raise forms.ValidationError("Requested slot is already booked, please choose another time") class Meta: model = Booking fields = ('customer_name','qty_plts','cbm','delivery_date','delivery_time') widgets = {'delivery_date':DatePickerInput(options={"daysOfWeekDisabled":[0,6],"minDate":timezone.now().date().strftime('%Y-%m-%d')}), 'delivery_time':forms.Select(choices=HOUR_CHOICES)} views.py from django.shortcuts import render # Create your views here. from .models import Booking,Customer from .forms import BookingForm from django.urls import reverse,reverse_lazy from django.contrib import messages from django.contrib.auth.mixins … -
how to create update link in home page...?
views.py class UpdateEvents(UpdateView): model = Event fields = ['event_name','event_date','venue','description'] template_name = 'events/events_update.html' success_url = '/' url.py path('update_events/<pk>/',UpdateEvents.as_view(), name='update-events'), home.html : when i go this "update" link than show me 'The current path, {% url 'update-events' id=events.id % }, didn’t match any of these.' how to i create upadate link in home.py file??? <a class="btn btn-primary" href="{% url 'update-events' id=events.id %}">update</a> [this is error page][1] [1]: https://i.stack.imgur.com/BIhqX.png -
How to block page access to other logged in user in django?
I am trying to block logged in user to access other user update profile page. My situation: Suppose Person A is logged in to his profile and he know other user update profile URl. In this situation he can simple getting access of the update profile url of other user. So , here i want to limit this restriction only to the same logged in user to update their profile only. this is my code for updating profiles: @login_required def UpdateProfile(request, slug): user = Profile.objects.get(slug=slug) if request.method == "POST": form = UpdateProfileForm(request.POST, request.FILES, instance=user) if form.is_valid(): profile_pic = form.cleaned_data['profile_pic'] form.profile_pic = profile_pic form.save() messages.success(request,"Data Updated successfully") return HttpResponseRedirect(reverse('updateaddress', args=(request.user.profile.slug,))) else: messages.error(request, "Please check all fields are valid") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: form = UpdateProfileForm(instance=user) context = { 'user':user, 'form':form, } return render(request, "authentication/register/update/profile.html",context) urls.py path("<slug:slug>/update-profile/", UpdateProfile, name="updateprofile"), -
Can django prefetch related work with 3 lookups?
I want to prefetch 3 tables plus the initial table. Here are model examples of the project i am working on class ExampleOne(models.Model): name = models.Charfield() option = models.BooleanField() money = IntegerField() class ExampleTwo(models.Model): word = models.Charfield() example_one = models.ManyToManyField(ExampleOne) number = IntegerField() class ExampleThree(models.Model): number = models.IntegerField() example_two = models.ForeignKey(ExampleTwo) def get_calculation_one(self): Calculate using data from Example_2 and Example_1 class ExampleFour(models.Model): date = models.DateField() example_three = models.ManyToManyField(ExampleThree) def get_calculation_two(self): Calculate using data from method on Example_3 Now I want to know if it is possible to retrieve data from all these models with as little hits to the database as possible because when I try to retrieve data it takes over one minute to retrieve the data and send it to the frontend The calculation might be making many database hits in order to get the data and calculate and i think that is why it is taking more than a minute to retrieve the data my view looks like this qs = ExampleFour.objects.prefetch_related( Prefetch('example_three__example_two__example_one') ).filter(...) Is there a way to use prefetch to make the retrieval faster or is there another suggestion on I can rewrite my code in order to avoid this long retrieval time? Note I …