Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot get the result of celery group with AsyncResult
I am using django cache to store the id of the celery group. Then I need to retrieve it from cache and get the result of group. cel_group = celery_group(tasks) //tasks is list of some celery tasks to be executed res = cel_group() children = [task.id for task in res.children] cache.set('some_key', res.id) return Response({'task_id': res.id,'children': children,'status': 'PENDING'}) So, here it stores the id of res. However, when I try to get the task from cached task id, it do not return the children. task_id_cached=cache.get('some_key') task=AsynResult(task_id_cached) print task_not_parent print task_not_parent.children >> 5e6fbfa3-691c-4e8f-b911-27a05ea122d3 >> None Who knows why ? -
Determine model instance from file URL
Given the URL in the request is for a known static file, how can I determine which model instance references that file? If I have several different Django model each with an ImageField, those fields each know how to store a relative path on the filesystem: # models.py from django.db import models class Lorem(models.Model): name = models.CharField(max_length=200) secret_icon = models.ImageField(upload_to='secrets') secret_banner = models.ImageField(upload_to='secrets') class UserProfile(models.Model): user = models.ForeignKey(User) secret_image = models.ImageField(upload_to='secrets') Templates can then render those images, using (for example) the instance.secret_banner.url attribute. When a request comes in for that same URL, I want to handle the request in a view: # urls.py from django.urls import path from .views import StaticImageView urlpatterns = [ ..., path(settings.MEDIA_URL + 'secrets/<path:relpath>', StaticImageView.as_view(), name='static-image'), ] So the StaticImageView.get method will be passed the relpath parameter parsed from the URL. At that point I need to do more handling based on which instance made the URL for this static image. # views.py from django.views.generic import View class StaticImageView(View): def get(self, request, relpath): instance = figure_out_the_model_instance_from_url_relpath(relpath) do_more_with(instance) What I don't know is how to write that figure_out_the_model_instance_from_url_relpath code. How can I use that path to find which model and which instance, generated that URL? -
django-allauth with facebook login error: callback uri is using http
I have deployed my app using django-allauth for facebook login. As you may know, facebook login requires a callback url that uses https. The app domain runs on https but the facebook receives the callback url with the http protocol, thus cannot login. I read through the code of allauth/socialaccount/providers/views/OAuth2Adapter and it handles the redirect_uri_protocol which by default is set to None. The method get_callback_url calls build_absolute_url which is looking for DEFAULT_HTTP_PROTOCOL in settings. Am I missing something here or I should just add DEFAULT_HTTP_PROTOCOL to the account settings? I couldn't find any documentation or similar issues on this. -
How to limit the amount of posts on a page in django blog
I built this django blog following along with a tutorial. It's all done but I need to limit the amount of posts displayed on the home view so the page just doesn't go on forever with every post ever made. views.py class HomeView(ListView): model = Post template_name = 'home.html' cats = Category.objects.all() #ordering = ['post_date'] ordering = ['-id'] def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(HomeView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu return context models.py class Post(models.Model): title = models.CharField(max_length=255) attatch_image = models.ImageField(null=True, blank=True, upload_to="images/") author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank=True, null=True) #body = models.TextField() post_date = models.DateField(auto_now_add=True) snippet = models.CharField(max_length=255) category = models.CharField(max_length=255, default='uncatigorized') likes = models.ManyToManyField(User, related_name='blog_posts') def total_likes(self): return self.likes.count() def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): #return reverse('article-detail', args=(str(self.id))) return reverse('home') home.html {% for post in object_list %} <div class="card" style="background-color: #E6FEFF;"> <div class="card-body"> <li><strong><a href="{% url 'article-detail' post.pk %}">{{ post.title }}</a></strong> - <span class="badge badge-success"><a href="{% url 'category' post.category|slugify %}" style="color:white">{{ post.category }}</a></span> <b>- {{post.author.username}}</b> - {{post.post_date}} {% if user.is_authenticated %} {% if user.id == post.author.id %} <small>✏️<a href="{% url 'update_post' post.pk %}">[Edit]</a> ❌<a href="{% url 'delete_post' post.pk %}">[Delete]</a></small><br/> {% endif %} {% endif %} <br/> {{ post.snippet … -
Django redirect with GET to url but webpage not changing in browser
"GET /login/ HTTP/1.1" 200 0 This appear in the log but page not changing to login page.. It only refresh the page after submit. I make the redirect like this return redirect("main:login") but it doesn't work. view.py view.py main/urls.py main/urls.py -
Is there a tool in django like ruby on rails scaffolding?
I`m starting to learn django development and i would like to know if like ruby on rails django comes with a scaffolding feature to generate templates files and views -
Django Logging Filter with KeyError
I have trouble with the Django logging and setting the custom filter. This is my current settings: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'filters': { 'user_filter': { '()': 'myapp.user_logging_filter.UserFilter', } }, 'formatters' : { 'standard': { 'format': '%(asctime)s [%(levelname)s] %(name)s %(current_user)s %(message)s' }, }, 'handlers': { 'default': { 'level': 'DEBUG', 'filters': ['user_filter'], 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'logs/debug.log', 'maxBytes': 1024*1024*10, # 10 MB 'backupCount': 5, 'formatter': 'standard', }, 'django': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'logs/django.log', 'maxBytes': 1024*1024*10, # 10 MB 'backupCount': 5, 'formatter': 'standard', }, }, 'loggers': { 'my': { 'handlers': ['default'], 'level': 'DEBUG', 'propagate': True }, 'django': { 'handlers': ['django'], 'level': 'DEBUG', 'propagate': True }, } } and the filter class is currently: import logging class UserFilter(logging.Filter): def filter(self, record): print('INSIDE') record.current_user = 'Marko' return True I get the error stack: --- Logging error --- Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/handlers.py", line 71, in emit if self.shouldRollover(record): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/handlers.py", line 187, in shouldRollover msg = "%s\n" % self.format(record) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/__init__.py", line 839, in format return fmt.format(record) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/__init__.py", line 579, in format s = self.formatMessage(record) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/__init__.py", line 548, in formatMessage return self._style.format(record) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/__init__.py", line 391, in format return self._fmt % record.__dict__ KeyError: 'current_user' Call stack: File … -
Django data not being inserted into postgresql
This codes gets the system performance reading using flask and plots it on a Django webpage using Chart which refreshes every second. I am trying to store the data into postgresql however it is not working. No data is being inserted into the table that was created in the database. views.py from django.shortcuts import render import requests from django.http import HttpResponse, request from .models import Usage def monitor(request): url = "http://127.0.0.1:5000/stats" data = requests.get(url) print(data.text) data2 = data.text return render(request, "home.html", {'alldata': data2}) def cpu_monitor(request): url = "http://127.0.0.1:5000/cpu" cpu_data = requests.get(url) cpu_data2 = cpu_data.json() for key in cpu_data2: cpu = cpu_data2['CPU'] time = cpu_data2['Time'] print(cpu) print(time) val = key return render(request, "chart.html", {'data': val}) def cp(request): url = "http://127.0.0.1:5000/cpu" cpu_data = requests.get(url) cpu_data2 = cpu_data.json() for key in cpu_data2: cpu = cpu_data2['CPU'] time = cpu_data2['Time'] print(cpu) print(time) val = [cpu] return HttpResponse(val) def mm(request): url = "http://127.0.0.1:5000/memory" memory_data = requests.get(url) memory_data2 = memory_data.json() for key in memory_data2: memory = memory_data2['Memory Percentage'] time = memory_data2['Time'] print(memory) print(time) mem = [memory] return HttpResponse(mem) def dk(request): url = "http://127.0.0.1:5000/disk" disk_data = requests.get(url) disk_data2 = disk_data.json() for key in disk_data2: disk = disk_data2['Used Partition'] time = disk_data2['Time'] print(disk) print(time) dsk = [disk] return HttpResponse(dsk) … -
how to convert this code to django requests?
/** This example uses comments and variables for clarity. These are not used in JSON. Do not include these comments or verbatim variable strings in your batch request. To batch multiple requests in one call, use the following POST HTTP request, and use the following request body syntax. POST https://www.googleapis.com/batch/reseller/v1 */ POST /batch/reseller/v1 HTTP/1.1 Authorization: auth_token Host: host Content-Type: multipart/mixed; boundary=batch_foobar Content-Length: total_content_length --batch_foobar Content-ID: %lt;item1:xxx@example.com%gt; Content-Type: application/http Content-Transfer-Encoding: binary POST /apps/reseller/v1/customers/example.com/subscriptions?customerAuthToken=token value Content-Type: application/json Content-Length: part_content_length { "kind":"subscriptions#subscription", "customerId":"example.com", "skuId" : "Google-Drive-storage-20GB", "plan" : { "planName": "FLEXIBLE" }, "seats": { "kind": "subscriptions#seats", "maximumNumberOfSeats": 10 }, "purchaseOrderId": "purchase-id-1" } --batch_foobar Content-ID: %lt;item2:xxx@example.com%gt; Content-Type: application/http Content-Transfer-Encoding: binary POST /apps/reseller/v1/customers/resold.com/subscriptions?customerAuthToken=token value Content-Type: application/json Content-Length: part_content_length { "kind":"subscriptions#subscription", "customerId":"resold.com", "skuId" : "Google-Apps-For-Business", "plan" : { "planName": "ANNUAL_MONTHLY_PAY" }, "seats": { "kind": "subscriptions#seats", "numberOfSeats": 10 } } --batch_foobar-- -
Django File Upload - form.is_valid() always false
Any help would be greatly appreciated. I am just starting with Django and ran into this issue. I have tried doing just a form as well without a model but still no luck. Here is my form html <form enctype="multipart/form-data" action="/upload" method="post"> {% csrf_token %} <input id="your_image" type="file" name="your_image"> <input class="upload-button" type="submit" value="Upload Now"> </form> Here is my views method from .forms import UploadFileForm from .models import UploadFileModel def upload(request): form = UploadFileForm() if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): print("file uploaded!") return render(request, 'pages/index.html') else: print("no luck") return render(request, 'pages/index.html') else: print("other function") return render(request, 'pages/index.html') Here is my models.py from django.db import models class UploadFileModel(models.Model): file = models.FileField(upload_to='images') def __str__(self): return self.file And here is my forms.py from django import forms from .models import UploadFileModel class UploadFileForm(forms.ModelForm): class Meta: model = UploadFileModel fields = ['file'] -
Django queryset param value auto change?
I have problem with parameter value pass into queryset This is my code recognition_date = str(recognition_date_arr[index]) print(recognition_date) data = EntryExitHistory.objects.filter(company_id=company_id, account_id=account_id, recognition_date=recognition_date) print(data.query) this is print output 2020-08-22 13:29:33 /home/ubuntu/.local/lib/python3.8/site-packages/django/db/models/fields/__init__.py:1365: RuntimeWarning: DateTimeField EntryExitHistory.recognition_date received a naive datetime (2020-08-22 13:29:33) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" SELECT `entry_exit_history`.`recognition_date`, `entry_exit_history`.`recognition_status`, `entry_exit_history`.`recognition_result`, `entry_exit_history`.`recognition_image_path`, `entry_exit_history`.`integration_code`, `entry_exit_history`.`company_id`, `entry_exit_history`.`account_id`, `entry_exit_history`.`device_id` FROM `entry_exit_history` WHERE (`entry_exit_history`.`account_id` = 2 AND `entry_exit_history`.`company_id` = 1 AND `entry_exit_history`.`recognition_date` = 2020-08-22 04:29:33) ORDER BY `entry_exit_history`.`recognition_date` ASC i don't know why value of recognition_date auto change from '2020-08-22 13:29:33' to '2020-08-22 04:29:33' -
Issue: Datatable Server Side Processing in Django
I am totally new in Django. I am trying to implement datatable server side processing.I have written some codes in my models.py , views.py and urls.py and followed Datatables official documentation also. But unfortunately I am getting error in my terminal and cant able to figure it out how can I fix it. Here is , models.py from django.db import models class Products(models.Model): title = models.CharField(max_length=100, blank=True) description = models.TextField(blank=True) price = models.IntegerField(blank=True, null=True) def __str__(self): return self.title views.py from django.shortcuts import render from ajax_crud.models import Products from django.http import JsonResponse def product_json(request): products_json = Products.objects.all().values('title', 'description', 'price') data = list(products_json) value = JsonResponse(data, safe=False) print(value) return value urls.py from django.urls import path from ajax_crud.views import product_json urlpatterns = [ path('json/',product_json,name='json'), ] demo-datatbles.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"> </head> <body> <h1>List of Products</h1> <hr> <table id="demo-table"> <thead> <tr> <th>title</th> <th>description</th> <th>price</th> </tr> </thead> <tbody></tbody> </table> <script src="//code.jquery.com/jquery-3.3.1.min.js"></script> <script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> <script> $(document).ready(function() { $('#demo-table').DataTable( { "processing":true, "serverSide": true, "ajax": { "type" : "GET", "url": "{% url 'json' %}", "dataSrc": "objects" }, "columns": [ { "data": "title" }, { "data": "description" }, { "data": "price" }, ] } ); } ); </script> </body> </html> My error in terminal. … -
How to login to django application for unit test, I am getting response code as 301 for every view
I am trying to login first then test other methods in view. We have keycloak integrated with django application. c = Client() login = c.login(username='admin', password='12345') self.assertTrue(login) //this succeed response = self.client.get('other view') self.assertEqual(response.status_code, 200) // getting 301!=200 error Could you please help with the login, so that it will not redirect! thanks. -
Form data display on terminal & doesn't save in postgres database django
In my cause of learning django, I decided to start with small projects, I'm working on a simple registration page. I have my form on the home page (index.html). And I have a view.py page I pass all the data from the form to my postgres db. I realise data does not save in db, instead all the registration data display in terminal and the url bar. Here's my code; Form (index.html) <form action="/index/" method="POST"> {% csrf_token %} <div><p><label for="fName">First Name</label></div> <div><input type="text" name="fName"></input></div> </p> <p> <label for="lName">Last Name</label> <input type="text" name="lName"></input> </p> <p> <label for="email">Email</label> <input type="text" name="email"></input> </p> <div><p><label for="uName">Username</label></div> <div><input type="text" name="uName"></input></div> </p> <p> <label for="password1">Password</label> <input type="password" name="Password1"></input> </p> <p> <label for="password2">Confirm Password</label> <input type="password" name="Password2"></input> </p> <div> <p><input type="submit"></input></p> </div> </form> views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth def index(request): if request.method == 'POST': first_name = request.POST['fName'] last_name = request.POST['lName'] username = request.POST['uName'] password1 = request.POST['password1'] password2 = request.POST['password2'] email = request.POST['email'] user = User.objects.create_user(username=username, password=password1, email=email, first_name=first_name, last_name=last_name) user.save() print('user created') return redirect('/') else: return render(request, 'index.html') I suspect the data is collected and them skip to executed this return render(request, 'index.html') because after I enter submit, the home page(index.html) … -
Django Mock an imported function used in a class function as part of a unit test
So I'm writing tests for my django application and I have successfully mocked quite a few external api calls that aren't needed for tests however one is tripping me up which is send_sms. To start here is the code: a/models.py: from utils.sms import send_sms ... class TPManager(models.Manager): def notification_for_job(self, job): ... send_sms() ... class TP(models.Model): objects = TPManager() ... p/test_models.py: @patch('a.models.send_sms') @patch('p.signals.send_mail') def test_tradepro_review_job_deleted(self, send_mail, send_sms): job = Job.objects.create( tradeuser=self.tradeuser, location=location, category=category, details="sample details for job" ) The Job object creation triggers TP.objects.notification_for_job via its perform_create method here: p/views.py: def perform_create(self, serializer): job = serializer.save(tradeuser=self.request.user.tradeuser) if settings.DEV_MODE: from a.models import TP job.approved = True job.save() TP.objects.notification_for_job(job) I have tried mocking a.models.TP.objects.notification_for_job, utils.sms.send_sms, a.models.TPManger.notification_for_job all to no avail. This is a pretty complex flow but I believe I have tried the main mock candidates here and was wondering if anybody knows how to either mock the notification_for_job function or send_sms function properly mostly just to prevent these api call that inevitably fail due to my test environment. Any ideas are greatly appreciated! -
How to implement a join query in django on a model with foreign keys
everyone. I want to implement a "following" function on my Profile model in django. i have a relationship model and i want to join both fields so that i can select the user that maches the query. I know peewee and i'll do something like the following: def following(self): return ( User.select().join(Relationship, on=Relationship.to_user).where(Relationship.from_user == self)) but i haven't been able to find how to make join queries in django. This are the models i have on models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) joined_at = models.DateTimeField() class Meta: ordering = ['-joined_at'] def __str__(self): return f'{self.user.username} profile' def following(self): """ I want to implement the query here. """ class Relationship(models.Model): from_user = ForeignKey(User, related_name='relationships') to_user = ForeignKey(User, related_name='related_to') -
Integrating Graphs with Django
I'm building my portfolio-site and I wanted to show my skills with the Graph. That will be a more creative way to represent skills I guess. I don't want to use complex libraries like D3.js and Django-graphos I want to keep it simple. any Suggestions? -
Adding items in a model
I'm working on a project where I've to add the first and second semester scores together. I summed up the first semester results in my models and also for the second semester also. But I've difficult summing the two models i.e the first and second. Here's my code for better understanding. Class First (models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) midscore = models.FloatField() finalscore = models.FloatField() def__str__(self): return self.user def get_total_first_score(self): return self.midscore + self.finalscore Class Second (models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) midscore = models.FloatField() finalscore = models.FloatField() def__str__(self): return self.user def get_total_second_score(self): return self.midscore + self.finalscore Now, how can I add the ger_total_score for the two semester. I tried something like this, but it's not giving me any results, since it's not under any model. def get_total_scores: get_total_first_score + get_total_second_score -
Django Inline formset validation with clean_<fieldname>() method
It's there anywhere validate the inline formset data with the clean_ "fieldname"() method instead of clean() method, the clean_"fieldname"() method is work in ModelForm but not in BaseInlineFormSet, I am tried browsing around, but no luck for me. class StockTransactionForm(forms.ModelForm): # clean() method def clean(self): to = self.cleaned_data.get('t') from = self.cleaned_data.get('from') # clean_<field>() method def clean_to(self): to = self.cleaned_data.get('t') return to class StockHistoryInlineFormSet(BaseInlineFormSet): class Meta: model = StockHistory fields = '__all__' # not working def clean_quantity(self): raise forms.ValidationError('tears') -
'str' object has no attribute 'as_view' in django
I am calling a class view inside class.Call_view value is "InsertionOrder" but it does not work instead directly writing 'InsertionOrder' works.Value is dynamic so i cant directly write 'InsertionOrder'.How to do this? Error shows: 'str' object has no attribute 'as_view' in django class GenericDetailView(APIView): def put(self, request,pk, format=None): url_name = request.resolver_match.url_name call_view = url_name.split("_")[0].title().replace('-', '') return call_view.as_view()(request._request, format) this does not # return InsertionOrder.as_view()(request._request, format) this works class InsertionOrder(APIView): #Code goes on -
How to configure both Memcache and database cache in the Django project
I am working with the Django project and get to know about the cache and its benefits. I had implement database cache and Memcache at the different project. Here is the config of the database cache. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'my_cache_table', } } python manage.py createcachetable Here is the config of Memcache. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } Note: Make sure you install this package. pip install pymemcache Problem: I wanted to use both caching in a single project. -
Django 3.1 | Django administration broken
I recently updated a Django project I had from 3.0 to 3.1 Everything seemed to work just fine, however, when rendering the page in Django administration (.../admin) everything was off-balance Here is what it looks like As you can see, if I zoom out the information is over there but, the scale is not correct. -
DJango>ConnectionRefusedError>App function that sends Password reset email
Good evening, I am having an issue in which I have built an app with a "Reset_Password_Email" function that sends an email to selected admin that allows them to reset their password. However when I submit my email I get a "ConnectionRefusedError at /accounts/password_reset/ [WinError 10061] No connection could be made because the target machine actively refused it" In the Tutorial it suggests that I add EMAIL_HOST = "localhost" and EMAIL_PORT = 1025 and that I run ''' python -m smtpd -n -c DebuggingServer localhost:1025 ''' in Powershell, but when I run it, I get no output, and when I attempt to send my email after leaving Powershell because of it's lack of an output and I run my server for my app, I am still faced with this crisis. Please help, and if there is any additional information that I can bring, feel free to let me know. Thank you! -
Having an error in creating contact us page in django?
models.py class Contact(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) message = models.TextField(max_length=400) def __str__(self): return f"{self.first_name} {self.last_name}" forms.py class ContactForm(ModelForm): class Meta: model = Contact fields = ["first_name", "last_name", "message"] widgets = { "message": Textarea( attrs={ "placeholder": "Xabaringizni kiriting!" } ) } project urls.py from django.contrib import admin from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^$',views.HomePage.as_view(), name='home'), url(r'^admin/', admin.site.urls), url(r'^blog/', include('blog.urls',namespace='blog')), #url(r'^blog/',include('django.contrib.auth.models.urls')), url(r'^about/', views.AboutPage.as_view(),name='about'), #url(r'^contact/', views.ContactPage.as_view(),name='contact'), ] blog/urls.py from django.urls import path from . import views from . import models #Template tagging app_name = 'blog' urlpatterns = [ path('', views.PostList.as_view(template_name='index.html'), name='index'), path('<slug:slug>/', views.post_detail, name='post_detail'), path("contact/", views.ContactCreate.as_view(template_name='contact1.html'), name="contact"), path("thanks/", views.thanks, name="thanks"), ] blog/views.py from django.shortcuts import render, get_object_or_404 from django.views import generic from django.views.generic import ListView,DetailView,CreateView from .models import Post, Contact from django.urls import reverse_lazy from django.http import HttpResponse from .forms import CommentForm,ContactForm class ContactCreate(CreateView): model = Contact form_class = ContactForm success_url = reverse_lazy("thanks") def thanks(request): return HttpResponse("Rahmat Siz bilan tez orada bog`lanamiz!") contact_page/contact1.html all my pages are linked like this in navigation bar <nav class="navbar navbar-expand-sm navbar-dark bg-dark"> <div class="container"> <a href="{% url 'home' %}" class="navbar-brand"><i class="fas fa-balance-scale">iLawyer.uz</i></a> <button class="navbar-toggler" data-toggle="collapse" data-target="#navbarCollapse"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a … -
Django ORM using distinct disrupts other order_by parameters
Why does adding .distinct() to my query totally screw up the order_by() logic? I have the following query (Postgres backend): sort_order = '-car__cardate' statements = CarModel.objects.only( 'car__car_id', 'car__cardate', 'car__title', 'car__location', 'model__name' ).select_related( 'car', 'candidate', ).extra( select={ 'is_position_setting': 'type_id = 7', 'is_null_date': 'cardate IS NULL', 'shorttitle': extra, }, ).filter(**kwargs).order_by('is_position_setting', 'is_null_date', sort_order) If I only want a queryset that contains unique car__car_id items, I try updating the order_by to this: order_by('car__car_id', 'is_position_setting', 'is_null_date', sort_order) and adding distinct thusly: distinct('car__car_id', 'is_position_setting', 'is_null_date', sort_order) this results in a deduped queryset but all other ordering/sorting is ignored. What am I doing wrong here? All I can seem to get is either a non-dedupe ordered queryset to my specified ordering OR just a deduped no-ordered queryset. Tried to follow what's described here: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#distinct