Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Iterating over large querysets in Django
How do you efficiently iterate over a large queryset (records in the millions) with Django? I'm trying to delete several million records that I can't do with a simple bulk SQL DELETE statement because the transaction would consume too much server memory. So I'm attempting to write a Python script to group ~10000 individual DELETE statements in a transaction. My script looks like: from django.db import transaction from django.conf import settings settings.DEBUG = False qs = MyModel.objects.filter(some_criteria=123) total = qs.count() i = 0 transaction.set_autocommit(False) for record in qs.iterator(): i += 1 if i == 1 or not i % 100 or i == total: print('%i of %i %.02f%%: %s' % (i + 1, total, (i + 1) / float(total) * 100, record)) record.delete() if not i % 1000: transaction.commit() transaction.commit() This runs fine for the first 2000 records, but then errors with: Traceback (most recent call last): File "/project/.env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1512, in cursor_iter for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): File "/project/.env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1512, in <lambda> for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): File "/project/.env/lib/python3.7/site-packages/django/db/utils.py", line 96, in inner return func(*args, **kwargs) File "/project/.env/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/project/.env/lib/python3.7/site-packages/django/db/utils.py", line 96, in inner return func(*args, **kwargs) django.db.utils.ProgrammingError: … -
C:\Users\krish\Desktop\code\hello> docker-compose up can't find a suitable configuration file in this directory or any parent: not found
when i run this command [docker-compose up] C:\Users\krish\Desktop\code\hello>docker-compose up can't find a suitable configuration file in this directory or any parent: not found i got this error {can anyone help me form this issue} -
Is there a way to display a user's sessions in django and expose them to an API?
I am building an authentication api and I am looking for a way to Query a database to the current user's logged in sessions Serialize them Exposes the to an API endpoint Here's the far I have gotten: My models.py from django.db import models from django.contrib.auth.signals import user_logged_in from django.contrib.sessions.models import Session from django.contrib.auth.models import User import datetime from django.utils import timezone class UserSession(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) session = models.ForeignKey(Session,on_delete=models.CASCADE) def all_unexpired_sessions_for_user(user): user_sessions = [] all_sessions = Session.objects.filter(expire_date__gte=datetime.datetime.now(tz=timezone.utc)) for session in all_sessions: print(session) try: session_data = session.get_decoded() except: pass print(session_data) #print(session_data['_auth_user_id']) print(type(user)) print(session_data.get('_auth_user_id')) if user.pk == session_data.get('_auth_user_id',''): try: user_sessions.append(session.pk) except: pass return Session.objects.filter(pk__in=user_sessions) I am able to display the session keys and the session data(please don't mind my million print statements) My Serializers.py from rest_framework import fields, serializers from .models import UserSession class UserSessionSerializer(serializers.ModelSerializer): class Meta: model = UserSession fields = ('user',) My views.py from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from .models import UserSession from django.contrib.sessions.models import Session from .serializers import UserSessionSerializer class AuthView(APIView): pass class SessionList(APIView): def get(self, request,format=None): user = request.user print(type(user)) all_sessions = UserSession.all_unexpired_sessions_for_user(user=user) print(all_sessions) serializers = UserSessionSerializer(all_sessions,many=True) return Response(serializers.data) def home_page(request): user = request.user #user_sessions = UserSession.objects.get_or_create(user=request.user,session_id =request.session.session_key) usr_ssn = … -
How to send ajax request from bootstrap 5 modal form?
I use Django and Bootsrap v5. I want to make authorization through modal forms. Instead of sending the form, a redirect on the endoint is happening. Can someone suggest an example? Without use of jQuery. -
How to retrieve data using id or pk in django
I am working on a project but after trying multiple way I still couldn't find the solution, I need to get the current room on the page so that user can leave room, I am aware it has to do with making queries or using pk,id. (My 1st question ever, sorry if not correct way to ask). **Views.py: def leave_room(request, room): room = request.GET['room.pk'] room_details = Room.objects.get(name=room) messages = Messages.objects.filter(room=room_details.pk) membership = RoomMember.objects.filter(user=request.user, room=messages) membership.delete() return redirect("/" urls.py: path("leave/<int:pk>/join/", views.leave_room, name="leave_room"), html: <a class="btn btn-danger" href="{% url 'leave_room' pk=room.pk %}">Leave Room</a>** -
How to use foreign key field's attribute for another model field
I have two models in different apps like so: class Account(models.Model): """ Class to store fiat account information of a companies bank account """ number = models.CharField(max_length=100) currency = models.ForeignKey(FiatCurrency, on_delete=models.CASCADE) owner = models.ForeignKey(Company, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.number class FiatTransaction(models.Model): """ Class to store Transactions made between escrow and operative white-listed fiat accounts """ debit_account = models.ForeignKey('company.Account', on_delete=models.CASCADE, related_name='debit_account') credit_account = models.ForeignKey('company.Account', on_delete=models.CASCADE, related_name='credit_account') executed_on = models.DateTimeField(auto_now_add=True) amount = models.FloatField() currency = debit_account.currency is_processed = models.BooleanField(default=False) fee = models.FloatField() memo = models.CharField(max_length=250) def __str__(self): return F"Transferred {self.amount} from {self.debit_account} to {self.credit_account} at {self.executed_on}" Now the field currency of model FiatTransaction doesn't seem to work the way I intend it to do. It raises AttributeError: 'ForeignKey' object has no attribute 'currency' # Source model class FiatCurrency(models.Model): """ A model to store Fiat Currencies offered by Finchin to include into cash-pools. """ ISO_Code = models.CharField(max_length=3) name = models.CharField(max_length=50) is_active = models.BooleanField(default=True) def __str__(self): return self.name Why's that and how to make this work? -
How do I update an SSL certificate in Python?
I am running python 3.9.1 I have some Django Admin Actions which create and then download some PDFs. When running this on my local machine (Windows 10) I have recently started getting the following error message: SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1123) Any ideas on how I can deal with this? The Django app works perfectly on the server, the problem is only on my local host. -
Merging multiple views with multi user into single html file in django
Alright, • I have project with multiuser login (developer and Project Manager) • Project manager opens ticket developer can accept ticket and complete ticket • Project manager can close ticket after developer marks completed I have implemented function based views and there is lot of repeating code in my implementation i have 8 html pages for developer & manager dashboard for open,accept,complete and closed tickets i need the function based views to be written in generic views listview and display the content according to the user logged in models.py ` class User(AbstractUser): is_developer = models.BooleanField(default=False) is_manager = models.BooleanField(default=False) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(unique=True) class Ticket(models.Model): ticket_title = models.CharField(unique=True,max_length=200) ticket_description = models.TextField() created_by = models.ForeignKey(User,related_name = 'created_by',blank=True,null=True,on_delete=models.CASCADE) STATUS_CHOICES = ( ('Opened','Opened'), ('Accepted','Accepted'), ('Completed','Completed'), ('Closed','Closed') ) status = models.CharField('Status',choices=STATUS_CHOICES,max_length = 100,blank=True,null=True) closed_date = models.DateTimeField(blank=True,null=True) completed_date = models.DateTimeField(blank=True,null=True) accepted_date = models.DateTimeField(blank=True,null=True) opened_date = models.DateTimeField(blank=True,null=True) accepted_by = models.ForeignKey(User,related_name='assigned_to',on_delete=models.CASCADE,blank=True,null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) ` views.py def manager_login(request): current = User.objects.filter(is_manager = True) if request.method == 'POST': pm_form = AuthenticationForm(data=request.POST) if pm_form.is_valid(): username = pm_form.cleaned_data.get('username') password = pm_form.cleaned_data.get('password') user = authenticate(username=username,password=password) if user is not None: if user in current: login(request,user) return redirect(reverse('pm_dashboard')) else: messages.error(request,"Invalid Username or Password") else: messages.error(request,"Invalid … -
2 Django projects on one IIS server under the same domain name
My goal is to create a dev environment for a Django project that I inherited. It is hosted on an IIS server and there is currently only a production environment server-side, which is being used by the clients at my university. I want to have a copy of the entire site that I can use for testing purposes. This copy would also use a separate database, which is a copy of the current database with some added tables. My initial thought was to have another branch of the git repo in the wwwroot folder, something like this: wwwroot/prod/django_project_files_here wwwroot/dev/django_project_files_here Both of these would hopefully use the same domain name, but use different urls and views in their respective urls.py and views.py files. For example, app.uniname.edu/home would tap the production version, whereas app.uniname.edu/dev-home would tap the dev version. All of the urls in the prod version would have a similar dev version with "dev" added to the url. I thought I had this all set up, but all of the urls in the second/dev version were 404s. This leads me to believe that the server is not actually using the second copy of the Django application. Granted, I'm not sure that … -
how to run simultaneous docker commands using asynchronous Django RESTAPI call
I am building a B2C Django application where I need to build multiple docker containers for each customer. I can call a single "docker run -d" commands using os_command from my rest API in Django. I am hosting it in Ubuntu 18.04. I can make multiple API calls from Django but in my Ubuntu host, it will delay the Docker commands unless the previous command is executed fully. I want to run multiple "docker run -d" commands to build containers for my customers. Is it possible to do it using an Asynchronous API call or does the Ubuntu system have a limitation to execute multiple commands simultenously? -
emerg "http" directive is not allowed here & server_names_hash
I am currently setting up my nginx .conf file with the following code server { listen 80; server_name ec2-13-59-58-36.us-east-2.compute.amazonaws.com; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/Shiftly/app.sock; } } However when I run sudo nginx -t I get an error like so :Dec 16 11:38:08 netzmelone nginx[14242]: nginx: [emerg] could not build the server_names_hash, you should increase server_names_hash_bucket_size: 32 I then add this code at the bottom of my .conf file or in my server file http { server_names_hash_bucket_size 64; } However this returns an error of nginx: [emerg] "http" directive is not allowed here in /etc/nginx/sites-enabled/django.conf:11 -
django: How to display ForeignKey elements using ListView
How can I use ListView to display ForeignKey elements? I don't know how to write in a template, so please let me know. My code is below. exp/models.py from django.db import models from users.models import User import uuid class Experiment(models.Model): experiment_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) subject = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) start = models.DateTimeField(null=True) users/models.py class User(AbstractBaseUser, PermissionsMixin): uuid = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) exp/urls.py from django.conf.urls import url from django.urls import include, path from django.contrib.auth import views as auth_views from . import views app_name = 'exp' urlpatterns = [ path('exp_data/', views.ExpList.as_view(), name='exp1_data'), ] exp/views.py class ExpList(ListView): model = Experiment1 template_name = 'experiment1_list.html' experiment1_list.html <table border="1"> <tr> <th>Full name</th> <th>Email</th> </tr> {% for data in object_list %} <tr> <td> {{ data.subjec.first_name }} {{ data.subjec.last_name }}</p> </td> <td>{{ data.subject }}</td> </tr> {% endfor %} </table> Results ------------------- |Full name|Email | |---------|-------| | |a@a.com| |---------|-------| | |b@b.com| ------------------- Expected results -------------------- |Full name |Email | |----------|-------| |John Smith|a@a.com| |----------|-------| |Jane Smith|b@b.com| -------------------- -
How to add more fields to the return response in django rest framework
I am trying to add more fields to the Response in the django rest framework to send to react frontend. This works fine @api_view(('GET',)) def get_status(request, task_id): task = current_app.AsyncResult(task_id) response_data = ImageSerializer(Image.objects.get(pk=task.get())) return Response(response_data.data, status=status.HTTP_201_CREATED) How can I add the json context below to the Reponse also? #How can I add the following to my response too context = {'task_status': task.status, 'task_id': task.id} -
How to write an asynchronous task in react for celery and django rest framework?
Here is my frontend react which checks if the task is pending, if it is pending then call getStatus again, if it is not pending anymore then pass it on to showCalculation getStatus = (obj) => { axios.get(`api/task/${obj.data.task_id}/`, {headers: {'accept':'application/json', }}, ).then(resp => { (obj.data.task_status === 'PENDING') ? this.getStatus(obj) : this.showCalculation(obj) }) } Here is my Django rest framework task @api_view(('GET',)) def get_status(request, task_id): task = current_app.AsyncResult(task_id) if task.status == 'SUCCESS': response_data = ImageSerializer(Test.objects.get(pk=task.get())) return Response(response_data.data, status=status.HTTP_201_CREATED) # the else statement is returning an error else: response_data = {'task_status': task.status, 'task_id': task.id} time.sleep(5) return Response(response_data, status=status.HTTP_400_BAD_REQUEST) How can I fix my else statement to return a response to the frontend so it checks again? {data: {…}, status: 400, statusText: 'Bad Request', headers: {…}, config: {…}, …} config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …} data: {task_status: 'PENDING', task_id: '83938b81-4031-4522-ac56-23dd77b9ce6e'} headers: {content-length: '74', content-type: 'application/json'} request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} status: 400 statusText: "Bad Request" [[Prototype]]: Object -
Mixed Content issue in Django
Getting the below error message while downloading the file from frontend , The front end url uses Https but the backend Django API url serving the file is http. New to django ,kindly help in sorting this out Mixed Content: The site at 'https://frontend.com/' was loaded over a secure connection, but the file at 'http://backend.com/user_summary/' was loaded over an insecure connection. This file should be served over HTTPS. -
What is the proper way of achieving a browsable API that expects data from 2 tables but writes to one and then another not in the first set of tables?
I have a Django project where I have 3 Models X: from django.contrib.postgres.functions import RandomUUID from django.db import models class X(models.Model): id = models.UUIDField(primary_key=True, default=RandomUUID) name = models.CharField(max_length=100) Y: from django.contrib.postgres.functions import RandomUUID from django.db import models class Y(models.Model): id = models.UUIDField(primary_key=True, default=RandomUUID) name = models.CharField(max_length=100) and XY: from django.contrib.postgres.functions import RandomUUID from django.db import models from my_app.models import X from my_app.models import Y class XY(models.Model): id = models.UUIDField(primary_key=True, default=RandomUUID) x_id = models.ForeignKey(X, on_delete=models.CASCADE, db_column='x_id') y_id = models.ForeignKey(Y, on_delete=models.CASCADE, db_column='y_id') and a default ModelSerializer for each of them: class XSerializer(serializers.ModelSerializer): class Meta: model = X fields = ['id', 'name'] class YSerializer(serializers.ModelSerializer): class Meta: model = Y fields = ['id', 'name'] class XYSerializer(serializers.ModelSerializer): class Meta: model = XY fields = ['id', 'x_id', 'y_id'] and I´d like to somehow, on get requests when retrieving X objects, to also show the XY objects related to it. On POST requests though, I'd like to be able to send the data for the X object with a nested field of many id's from the Y table and create an X object, retrieve the newly generated primary key of that X object and create as many XY objects as Y primary keys were sent with that … -
React to "click event" in Python (Django)
everyone, beforehand - I'm a bloody but motivated developer beginner. I am currently trying to react to simple events (click on a button) in the HTML code in my Django project. Unfortunately without success ... HTML: <form> {% csrf_token %} <button id="CSVDownload" type="button">CSV Download!</button> </form> JavaScript: <script> document.addEventListener("DOMContentLoaded", () => { const CSVDownload = document.querySelector("#CSVDownload") CSVDownload.addEventListener("click", () => { console.dir("Test") }) }) </script> Do I need JavaScript for this? Or is there a way to react directly to such events in python (Django)? I am really grateful for all the support. Since I'm not really "good" yet - a simple solution would be great :) Python (Django) if request.method == "POST": projectName = request.POST["projectName"] rootDomain = request.POST["rootDomain"] startURL = request.POST["startURL"] .... With this, for example, I managed to react to a kind of event, i.e. when the user sends the form. The problem here, however, is - if I have several forms on one page, then I cannot distinguish which function should be carried out: / I am at a loss -
Django Database issues after deploying to Heroku
I am having this issue below since deploying to Heroku. Depending on the page, the model causing the error changes, but the issue is still the same across. The example I will provide, gets triggered from the trailer-locations/ page. Environment: Request Method: GET Request URL: https://nameless-ravine-45956.herokuapp.com/trailer-locations/ Django Version: 3.2.6 Python Version: 3.10.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.home', 'apps.config'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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') Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (column home_trailerlocation.statusCode does not exist LINE 1: ...State", "home_trailerlocation"."locationCountry", "home_trai... ^ ) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/app/apps/home/views.py", line 103, in trailerLocations timestamp = trailers[0]['trailerlocation__updated_at'] File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/query.py", line 317, in __getitem__ qs._fetch_all() File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/query.py", line 109, in __iter__ for row in compiler.results_iter(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size): File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1130, in results_iter results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size) File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1175, in execute_sql cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 98, in … -
Django - Annotating an aggregation of annotations on related objects
I have three models: class Document(BaseModel): def total_price() return DocumentLine.objects.filter( section__in=self.sections.all() ).total_price() class Section(BaseModel): document = ForeignKey(Document, on_delete=CASCADE, related_name='sections') class LineQuerySet(QuerySet): def with_total_price(self): total_price = F('quantity') * F('price') return self.annotate( total_price=ExpressionWrapper(total_price, output_field=DecimalField()) ) def total_price(self): return self.with_total_prices().aggregate( Sum('total_price', output_field=DecimalField()) )['total_price__sum'] or Decimal(0.0) class Line(BaseModel): objects = LineQuerySet.as_manager() section = ForeignKey(Section, on=delete=CASCADE, related_name='lines') price = DecimalField() quantity = DecimalField() As you can see on the LineQuerySet, there is a method that will annotate the queryset with the total price of each line, based on the price and quantity. Now I can easily get the total price of an entire document doing something like this: document = Document.objects.get(pk=1) total_price = document.total_price() However, now I would like to generate a queryset of multiple documents, and annotate that with each document's total price. I've tried a combination of annotates, aggregates, making use of prefetch_related (using Prefetch), and OuterRef, but I can't quite seem to be able to get the result I want without it throwing an error. Is there some way to perform this operation in a queryset, making it then possible to filter or order by this total_price field? -
Django views page not found
I am trying to get the task_id of celery but the URLs is returning error not found Here is my URLs router = routers.DefaultRouter() router.register(r'analyze_im', ImageViewSet) urlpatterns = [ path('', include(router.urls)), path('task/<str:task_id>', TaskView.as_view()), ] Here is my serializer class TaskView(View): def get(self,request, task_id): task = current_app.AsyncResult(task_id) response_data = {'task_status': task.status, 'task_id': task.id} if task.status == 'SUCCESS': --some logic-- return JsonResponse(response_data) When I navigate to /api/analyze_im/task/e11c2a1d-91b6-44c7-befd-663884753d52it show Page not found (404) The current path, didn’t match any of these. , why is that? When I do the following http://localhost:8000/api/analyze_im/task/ Django shows me the API view -
In Django, how can I have a function where I can only update the value instead of creating a new instance of it?
For example, I have a function in my views.py to post availability of food. However, I do not want the user to keep creating new instances of available food. I only want the user to be able to update that value. Right now, I have restricted the user to just create a food availability instance and then am not allowing the user to create another one. However, I do not want it as such; I want the user to be able to just update that number. This is what I have now: def check_existing_post(request): data = request.POST.copy() data["author"] = request.user if len(Food_Avail.objects.filter(author=request.user)) > 0: return False else: return True def post_available_food(request): instance = Food_Avail() data = request.POST.copy() data["author"] = request.user form = FoodAvailForm(data or None, instance=instance) if request.POST and form.is_valid() and check_existing_post(request): form.save() return HttpResponseRedirect(reverse("accounts:home")) else: messages.info( request, "food availability by restaurant has already been posted!" ) return render(request, "food_avail/post_food_avail.html", {"food": form}) -
Django looking for static files in contrib/admin and ckeditor
My app doesn't serve the embedded static files in my HTML my project structure is: main/ mediafiles/ resume/ settings.py ... static/ css/ images/ js/ settings.py: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "main", "ckeditor", ] STARICFILES_DIR = [ os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'media'), ] STATIC_URL = "/static/" STATIC_ROOT = BASE_DIR / "staticfiles" MEDIA_URL = "/media/" MEDIA_ROOT = BASE_DIR / "mediafiles" However, when I try python manage.py findstatic --verbosity 2 static/js/style.js I get the following: No matching file found for 'js/script.js'. Looking in the following locations: C:\Users\Bilal\Envs\django-env\lib\site-packages\django\contrib\admin\static C:\Users\Bilal\Envs\django-env\lib\site-packages\ckeditor\static Any idea where I might be going wrong? All the static file settings appear to be correct. Any help will be appreciated as I've been stuck on this one for a while -
Reduce db queries
my models class AssessmentTest(BasicModel): title = models.CharField(max_length=120, unique=True) class UserTestResult(BasicModel): assessment_test = models.ForeignKey(AssessmentTest, on_delete=models.CASCADE, related_name='users_passed') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='test_results') points = models.PositiveIntegerField(default=0) my views class AssessmentTestView(ReadOnlyModelViewSet): serializer_class = AssessmentTestSerializer queryset = AssessmentTest.objects.all() my serializers class AssessmentTestListSerializer(serializers.ModelSerializer): class Meta: model = AssessmentTest fields = [ 'id', 'title', 'user_results', ] user_results = serializers.SerializerMethodField() def get_user_results(self, obj: AssessmentTest): user = self.context['request'].user if not user.is_anonymous: test_result = UserTestResult.objects.filter(assessment_test=obj, user=user) if test_result: return UserTestResultSerializer(instance=test_result.last()).data return None When I try to get all tests, in get_user_results I face n+1 problem (for every test there is extra query to UserTestResult) Can I somehow avoid this? Maybe it's possible to use prefetch_related on reverse foreign_key in queryset? Or not? Can someone help? -
Check for a specific url and render jinja2 / html
How can check for a specific URL in jinja2 within html files and then render different html files based on what URL I am currently at? For eg. # if {{ request.path == /siteID/ }} {% include "file1.html" %} # if {{ request.path == /siteID/abcde/ }} {% include "file2.html" %} Current logic I have which I feel is not very good: <!-- ..... bunch of html lines .... --> {% if request.path|length > 8 and request.path.startswith('/siteID/') and request.path[8:].strip('/').split('/')|length == 1 %} {% include "file2.html" %} {% else %} {% include "file1.html" %} {% endif %} <!-- ..... bunch of html lines .... --> Also how do I scale this if I want to do something in the future like: # if {{ request.path == /siteID/abcde/uvwxyz }} {% include "file3.html" %} -
Advice on adding an ancestors ArrayField to a self-referential model in Django
I'm developing a Django app (Django 3.2.8, Python 3.9, PostgreSQL 13.4) that functions very much like an FTP service. For the folder/file structure I've created a self-referential model called "Instance", which also uses generic relations so that I can reuse/structure various content types under one another: class Instance(models.Model): parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') subscribers = models.ManyToManyField('users.Organization', blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') However, I'm finding that development is being limited/slowed by the need for raw CTE queries. And I'm thinking that the most elegant way (based on the views I require) to make this model fully ORM-accessible is to add an "ancestors" ArrayField. class Instance(models.Model): parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') ancestors = ArrayField(models.PositiveIntegerField(), null=True, blank=True, default=list) .... I was easily able to construct & add an array value to this field through my views/scripts with a function like: def get_ancestors(context_instance, ancestors_array): ancestors_array.append(context_instance.id) if context_instance.parent: return get_ancestors(context_instance.parent, ancestors_array) else: return list(reversed(ancestors_array)) However, I thought it would be far better to have the ancestors array value calculated and added whenever an instance of the "Instance" model was saved. I couldn't figure how it would be possible to query instances of a model …