Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to avoid Django Rest Framework logging extra info?
I am using Django Rest Framework. In settings.py I am using the following entry: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': str(BASE_DIR) + '/debugme.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } IN my code I just added logger.info('Checking Balance!') but when I checked debugme.log it dumped loads of unwanted info but the one I needed? Watching for file changes with StatReloader Waiting for apps ready_event. Apps ready_event triggered. Sending autoreload_started signal. Watching dir /muwallet_web/muwallet/locale with glob **/*.mo. Watching dir /usr/local/lib/python3.9/site-packages/rest_framework/locale with glob **/*.mo. Watching dir /usr/local/lib/python3.9/site-packages/django_extensions/locale with glob **/*.mo. Watching dir /muwallet_web/muwallet/api/locale with glob **/*.mo. (0.004) SELECT c.relname, CASE WHEN c.relispartition THEN 'p' WHEN c.relkind IN ('m', 'v') THEN 'v' ELSE 't' END FROM pg_catalog.pg_class c All I need to show info I need. -
Django - No CSRF error for posts without token
I'm using Django to host a React application. I added the CSRF protection middleware in Django. I tried testing it by sending a http post with Postman, without the x-csrftoken in the header. To my surprise, I did not get a 403, but I was able to get data without the x-csrftoken. How is this possible? Below you find my CSRF settings. My additional Django settings are very straightforward and include CORS. ... # Cross Origin Resource Sharing Protection CORS_ALLOWED_ORIGINS = [ 'http://127.0.0.1:3000', ] CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True # Cross Site Request Forgery Protection CSRF_TRUSTED_ORIGINS = [] MIDDLEWARE = [ ... 'django.middleware.csrf.CsrfViewMiddleware', ] -
Django: problem declarig 2 fields with the same related object
I'm trying to create a model that has 2 fields with the same related object (Call): class Call(LogsMixin, models.Model): """Definición del modelo de Proveedor.""" id = models.CharField("ID de la convocatoria", primary_key=True, null=False, default="", max_length=50) name = models.CharField("Nombre de convocatoria", null=False, default="", max_length=200) active = models.BooleanField("Activada", default=True) class Consumption(LogsMixin, models.Model): """Definición del modelo de Consumos""" client = models.ForeignKey('authentication.Client', verbose_name=("Cliente"), null=True, default=None, on_delete=models.SET_DEFAULT) sap_price = models.DecimalField(("Precio de SAP"), max_digits=6, decimal_places=2, null=False, default=0) access_date = models.DateField("Fecha de acceso", auto_now=False, auto_now_add=False) call = models.ForeignKey(Call, verbose_name=("Convocatoria"), null=True, default=None, on_delete=models.SET_DEFAULT) accessible_calls = models.ManyToManyField(Call, verbose_name=("Convocatorias accesibles")) When I try to make the migrations I receive the next error: ERRORS: consumptions.Consumption.accessible_calls: (fields.E304) Reverse accessor for 'Consumption.accessible_calls' clashes with reverse accessor for 'Consumption.call'. HINT: Add or change a related_name argument to the definition for 'Consumption.accessible_calls' or 'Consumption.call'. consumptions.Consumption.call: (fields.E304) Reverse accessor for 'Consumption.call' clashes with reverse accessor for 'Consumption.accessible_calls'. HINT: Add or change a related_name argument to the definition for 'Consumption.call' or 'Consumption.accessible_calls'. Does anyone have any clue? -
How to add load more button in django application
I have developed a template for viewing the images in my Django application.I want to view only 2 images at the starting and then after clicking the load more button, the next 2 images have to be shown. I am unable to do this. <div class="items"> {% for portfolio in portfolios %} <!-- ======= Portfolio Section ======= --> <section id="portfolio{{portfolio.id}}" class="portfolio"> <div class="container" data-aos="fade-up"> <div class="row portfolio-container" data-aos="fade-up" data-aos-delay="200"> <div class="col-lg-4 col-md-6 portfolio-item"> <img src="{{ portfolio.file.url }}" class="img-fluid" alt="{{ portfolio.title }}"> <div class="portfolio-info"> <h4>{{ portfolio.title }}</h4> <p style="font-size: 11px">Uploaded by <a href="{% url 'profile' username=portfolio.user.username %}">{{portfolio.user}}</a></p> <a href="{{ portfolio.file.url }}" onclick="views({{portfolio.id}})" data-gall="portfolioGallery" class="venobox preview-link" title="{{ portfolio.title }}"> <i class="bx bx-show-alt"></i> </a> <a href="{{ portfolio.file.url }}" onclick="dow({{portfolio.id}})" class="details-link" title="Download" download> <i class='bx bxs-download pl-2'></i> </a> <p id="views{{portfolio.id}}" >{{portfolio.views}}</p> <span id="dow{{portfolio.id}}">{{portfolio.total_downloads}}</span> {% if user.is_authenticated %} {% if user.username in portfolio.likes %} <button type="submit" onclick="like({{portfolio.id}});" name="post_id" id="ul{{portfolio.id}}" value="{{portfolio.id}}" class="btn btn-primary btn-sm"> Unlike </button> {% else %} <button type="submit" onclick="like({{portfolio.id}});" name="post_id" id="l{{portfolio.id}}" value="{{portfolio.id}}" class="btn btn-primary btn-sm"> Like </button> {% endif %} {% else %} <a class="btn btn-outline-info" href="{% url 'login' %}">Log in to like this article</a><br> {% endif %} </div> <strong class="text-secondary" >Total likes:<span id="total_likes{{portfolio.id}}">{{portfolio.number_of_liked}}</span></strong> </div> </div> </div> </div> </section> <!-- End Portfolio Section … -
How to serialize field dynamically if I don't know in advance which serializer will be chosen?
I have a simple serializer: class BoxSerializer(Serializer): modelName = serializers.CharField(required=True) body = ??? And I want to serialize a field 'body' depending on 'modelName ' field. For example, if modelName is 'Phone' then i want to use PhoneSerializer for 'body' field. If modelName 'book' i want to user BookSerializer and so on. How can i implement this? Please note that I am not going to save anything to the database -
Django maintain password history and compare passwords
I have a Profile model by extending the User model where I added the fields for the last 5 passwords and the last password change date. class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE) birth_date = models.DateField(null=True, blank=True) phone = models.CharField(max_length=10) status = models.CharField(max_length=10) role = models.CharField(max_length=10) pwd1 = models.CharField(max_length=256, blank=True) pwd2 = models.CharField(max_length=256, blank=True) pwd3 = models.CharField(max_length=256, blank=True) pwd4 = models.CharField(max_length=256, blank=True) pwd5 = models.CharField(max_length=256, blank=True) last_pwd_change_date = models.DateField(null=True, blank=True) I am able to force the password expiry date in the views.py like so lastpwddate= userProfile.last_pwd_change_date today=date.today() datediff=today-lastpwddate if datediff.days > 90: errorlogger.error("Password Expired") auth.logout(request) My next step would involve the following: Whenever a new user registers, the password they used will be stored in the pwd1 to pwd5 fields Whenever a user updates their password, I would like to compare the new password with the last 5 passwords. If there is any similar password among them, throw an error I am new to Django and since I am using the default code for password change etc. I am not sure how to proceed. Do I create a new view function or change any existing code in (possibly) the auth folder? How should I proceed? Any help is much appreciated. -
Django keras load_model raise OSError how to fix?
# image_predict.py import os file_path = os.path.join(settings.STATIC_URL, 'util/keras_model.h5') print(file_path) model = tensorflow.keras.models.load_model(file_path) i want to use keras model but it doesn't work. -
Multi-Stage Docker build failed - Error: invalid from flag value
I am trying to implement multi-stage docker build to deploy Django web app. An error occurred while trying to copy from one docker stage to another. I am sharing Dockerfile and error traceback for your reference. The same Docker build worked before one day ago. Somehow, It is not working today. I have searched for some workaround. But, no luck. My Dockerfile as: FROM node:10 AS frontend ARG server=local RUN mkdir -p /front_code WORKDIR /front_code ADD . /front_code/ RUN cd /front_code/webapp/app \ && npm install js-beautify@1.6.12 \ && npm install --save moment@2.22.2 \ && npm install --save fullcalendar@3.10.1 \ && npm install --save pdfjs-dist@2.3.200 \ && npm install \ && npm install --save @babel/runtime \ && yarn list && ls -l /front_code/webapp/app/static \ && npm run build \ && rm -rf node_modules \ && cd /front_code/webapp/market-app \ && yarn install \ && yarn list && ls -l /front_code/webapp/market-app/static \ && yarn build \ && rm -rf node_modules \ FROM python:3.8-alpine AS base ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ARG server=local ARG ENV_BUCKET_NAME="" ARG REMOTE_ENV_FILE_NAME="" ARG FRONT_END_MANIFEST="" ARG s3_bucket="" ARG AWS_ACCESS_KEY_ID="" ARG AWS_SECRET_ACCESS_KEY="" ARG RDS_DB_NAME="" ARG RDS_USERNAME="" ARG RDS_PASSWORD="" ENV server="$server" ENV_BUCKET_NAME="$ENV_BUCKET_NAME" REMOTE_ENV_FILE_NAME="$REMOTE_ENV_FILE_NAME" FRONT_END_MANIFEST="$FRONT_END_MANIFEST" s3_bucket="$s3_bucket" AWS_SECRET_ACCESS_KEY="$AWS_SECRET_ACCESS_KEY" AWS_ACCESS_KEY_ID="$AWS_ACCESS_KEY_ID" RDS_DB_NAME="$RDS_DB_NAME" RDS_USERNAME="$RDS_USERNAME" RDS_PASSWORD="$RDS_PASSWORD" RUN … -
Gitlab runner deletes Django media files on the server
I'm deploying a Django project on Centos 7 server using gitlab runner. Each time I commit and push the project, gitlab runner tries to remove folders (such as the media folder) that are not in the gitlab repository(are on .gitignore). I don't want gitlab runner to delete media files. How can I ignore deleting some files and folders when gitlab runner starts its job? -
How to allow Iframe to other website from Django Website?
I am new to Django. I have launched a new site with Django. I wish people can iframe my site. But when doing I frame, It shows Site Refused to connect. . As a newbie, I don’t have any idea what to do now. Would you please suggest me. Thanks in Advance -
Django - Issue with parsing multiselect values received as request.GET context parameter to a template
I had passed request.GET as context parameter to my template. I am planning to use populate multiselect dropbox with the values coming from request.GET in the colony tag. I have passed the context correctly from views.py file but I am not able to fetch the all the colony values in template. If I use values.colony, I just get the last value in this list. I am using following code views.py 'values': request.GET I am using value in values.getlist('colony') in the template file to retrieve all colony values but this line is giving error anytime I use values.getlist('colony'). Can you please suggest what I am doing wrong? -
Unable to create task in Redis
I am using Celery to create tasks, but after a while Redis returns an error Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/celery/worker/worker.py", line 203, in start self.blueprint.start(self) File "/usr/local/lib/python3.7/site-packages/celery/bootsteps.py", line 116, in start step.start(parent) File "/usr/local/lib/python3.7/site-packages/celery/bootsteps.py", line 365, in start return self.obj.start() File "/usr/local/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 311, in start blueprint.start(self) File "/usr/local/lib/python3.7/site-packages/celery/bootsteps.py", line 116, in start step.start(parent) File "/usr/local/lib/python3.7/site-packages/celery/worker/consumer/connection.py", line 21, in start c.connection = c.connect() File "/usr/local/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 400, in connect conn.transport.register_with_event_loop(conn.connection, self.hub) File "/usr/local/lib/python3.7/site-packages/kombu/transport/redis.py", line 1061, in register_with_event_loop cycle.on_poll_init(loop.poller) File "/usr/local/lib/python3.7/site-packages/kombu/transport/redis.py", line 336, in on_poll_init num=channel.unacked_restore_limit, File "/usr/local/lib/python3.7/site-packages/kombu/transport/redis.py", line 201, in restore_visible self.unacked_mutex_expire): File "/usr/local/lib/python3.7/contextlib.py", line 112, in __enter__ return next(self.gen) File "/usr/local/lib/python3.7/site-packages/kombu/transport/redis.py", line 121, in Mutex lock_acquired = lock.acquire(blocking=False) File "/usr/local/lib/python3.7/site-packages/redis/lock.py", line 187, in acquire if self.do_acquire(token): File "/usr/local/lib/python3.7/site-packages/redis/lock.py", line 203, in do_acquire if self.redis.set(self.name, token, nx=True, px=timeout): File "/usr/local/lib/python3.7/site-packages/redis/client.py", line 1801, in set return self.execute_command('SET', *pieces) File "/usr/local/lib/python3.7/site-packages/redis/client.py", line 901, in execute_command return self.parse_response(conn, command_name, **options) File "/usr/local/lib/python3.7/site-packages/redis/client.py", line 915, in parse_response response = connection.read_response() File "/usr/local/lib/python3.7/site-packages/redis/connection.py", line 756, in read_response raise response redis.exceptions.ReadOnlyError: You can't write against a read only replica. As I understand it, such problems arise when the task fails. It is important to note that I am using docker-compose. I am attaching an … -
How to refrence to an item in WishList for a Product in Django?
I want to implement a wishlist for the products in my Django site so that I can represent them in a wishlist page to the user. the products are in the products app. products.models.py class ControlValves(models.Model): title = models.CharField(max_length=50, unique=True) product_name = models.CharField(max_length=50, blank=True) .... class Accessories(models.Model): title = models.CharField(max_length=50, unique=True) description = models.CharField(max_length=50, blank=True) .... There is a services app that contains various services(models). Then I want to create a wishlist in users app. users.models.py class Wishlist(models.Model): owner = models.ForeignKey( User, on_delete=models.CASCADE) title = models.CharField(max_length=50, null=True, blank=True) item = models.ForeignKey( which_model_should_be_here??? , on_delete=models.CASCADE) since I am fetching the list of products and services from two different apps and within each, there are various models: question: 1- I don't know how to point to the selected product or service? should I declare a foreign key to each possible product model o services model, or there is another efficient way? 2- an example of how to load them to show to the user( i.e. how to write a query to load them from DB) would be great. I also checked the answer to this and this, but they are fetching products from just one model, so it's easy because there should … -
When djando DEBUG = False I am always thrown with a 500 server error
I am trying to create an eCommerce app and I still haven't got into the backend part of it but I was testing the Django debug feature when I am already thrown with an error. I am using Heroku as my web hosting provider. I am also using a couple of files from the static folder and have not stored them somewhere on the internet yet. Is that a possible error? This is my settings.py file... import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('EBLOSSOM_SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_cleanup', 'crispy_forms', 'storages', 'store.apps.StoreConfig', 'user.apps.UserConfig' ] 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', ] ROOT_URLCONF = 'eblossom.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'eblossom.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': … -
Regex for UnicodeUsernameValidator
In Django I set custom User where I set my own regular expression to valid a registered username field witch should accept 1 space between words and non before and after all name. What I do wrong? In https://regexr.com/ this expression work but in my form is not. username_validator = MyUnicodeUsernameValidator() @deconstructible class MyUnicodeUsernameValidator(validators.RegexValidator): regex = r'^([\w.@+-]+\s?[\w.@+-]*[^\s]){1,}$\Z' message = _( 'Enter a valid username. This value may contain only letters, ' 'numbers, and @/./+/-/_ characters. ' 'Whitespaces before/after the name, as well as two whitespaces between words are incorrect.' ) flags = 0 -
Django - Python - How to include STATUS CODE in response using JsonResponse?
Here is my code, that let users input their ID and Name to check if they are in a list of something. def some_api(requests): try: **do something** return HttpResponse('Your name is in the list') #Response 302 CODE FOUND NOT 202 except: return JsonResponse([{ ID : 123, #Response 203 CODE EMPTY NOT 202 Name : ABC, #with information for users to double check Content : [] #their params }]) As always, when I return HttpResponse and `JsonResponse, it is always the 200 CODE -
APScheduler job not executed as scheduled
I am trying to run apscheduler with gunicorn and supervisord. Without gunicorn, apscheduler is working but sometimes with gunicorn, apscheduler does not work. Except apscheduler, other project is working. I am using following command to run using gunicorn /home/ubuntu/project/project_folder/venv/bin/gunicorn project.wsgi:application --timeout 120 --workers 2 --threads=3 --bind=0.0.0.0:2732 In settings.py file from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.jobstores.redis import RedisJobStore from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor logging.basicConfig(filename='logs/scheduler', level=logging.DEBUG,format='[%(asctime)s]: %(levelname)s : %(message)s') logging.getLogger('apscheduler').setLevel(logging.DEBUG) # scheduler = BackgroundScheduler(misfire_grace_time=20, executors=executors) scheduler = BackgroundScheduler({'apscheduler.timezone': 'Asia/Calcutta'},job_defaults={'misfire_grace_time': None}) scheduler.add_jobstore(RedisJobStore(jobs_key='dev-jobs', run_times_key='dev_all_run_times'), 'redis') scheduler.start() And set the job in views.py file as start_date_of_job = model_object.start_date start_time = dates.strptime(model_object.start_time, '%I.%M %p').time() start_datetime_of_job = dates.combine(start_date_of_job, start_time) settings.scheduler.add_job(function_to_run, 'date', jobstore='redis', replace_existing=True, run_date=start_datetime_of_job, misfire_grace_time=None, id="start-" + str(model_object.id), args=[args list]) Sometimes it works, sometime it does not work. -
How to automatically create relationship between user model and custom group in Django?
As a newbie to Django, all things are still not clear to me. I'm having some issues while working on my project. Whenever I register as a new student, it lets me to login. But I cannot upload profile picture. It throws me an error: ValueError at /account_settings/ The 'profile_pic' attribute has no file associated with it. When I login as an admin and want to see the new student, I just see a blank space, not the new student. Here is the screenshot of my admin view: If I see from admin page, there is also a blank space. Here is admin page view: I have to manually create a student and an user from admin page, and make relationship between them. Please anyone explain me what actually happens behind the scenario. I'm a noob, I'll be grateful if anyone kindly makes it clear for me. Thanks in advance. Here is my models.py: from django.db import models from django.contrib.auth.models import User class Student(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(default= 'default-picture.jpg', null= True, blank= True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return str(self.name) class Tag(models.Model): name … -
DRF class based view parse dataObj ids from datatables
I am using datatables and my goal is to delete the selected rows. I can select the rows and get their IDs. The button #countbuttonids does this perfectly and send me an alert. However, when I try and post this data to my custom DRF endpoint I am having issues deleting the objects with the ID's in the data array. Two attempts below with their relating error messages. views.py 1 # https://www.django-rest-framework.org/tutorial/3-class-based-views/ class APIDeleteEntries(generics.RetrieveUpdateDestroyAPIView): queryset = Entry.objects.all() serializer_class = EntrySerializer def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) Error Message 1 assert lookup_url_kwarg in self.kwargs, ( AssertionError: Expected view APIDeleteEntries to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. [22/Dec/2020 10:11:21] "DELETE /api/delete-entries/ HTTP/1.1" 500 114337 views.py 2 # https://www.django-rest-framework.org/tutorial/3-class-based-views/ class APIDeleteEntries(generics.RetrieveUpdateDestroyAPIView): queryset = Entry.objects.all() serializer_class = EntrySerializer def delete(self, request, *args, **kwargs): entry_ids = self.kwargs['id'] return entry_ids.destroy(request, *args, **kwargs) Error Message 2 entry_ids = self.kwargs['id'] KeyError: 'id' entry_list.html {% extends "dashboard/base.html" %} {% load i18n %} {% block content %} <style> table.dataTable tbody tr.odd.selected { background-color:#acbad4 } table.dataTable tbody tr.even.selected { background-color:#acbad5 } </style> <!-- Page Heading --> <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h2 … -
Django 3.1.4: Get checkbox values in a function in views.py
I successfully did it for input text and now I would like to do it with checkboxes. I don't want to store checkbox values in a database. I just want to get it in a function in views.py I was not able to find how to do it. Thank you for your help! -
Why use Django Rest Framework if I can create an API using Django itself?
I have a Django API which is hosted in Ubuntu EC2 instance using Apache and mod_wsgi. Should I integrate the Django Rest Framework? If yes what are the advantages of using it over normal django API? -
Django template not extending in project
I have two app in Django. Blog and account blog -templates -base.html account -template -signup.html i want to extend base.html to signup.html {% extends 'blog/base.html' %} not working please help -
How to send push notification using django
I want to create a custom notification system using Django and javascript when the user enters his/her requirement and sends it then that will notify the owner. -
Django-Getting error as "self.fail("First argument is not valid JSON: %r" % raw)"
When i am trying to run the below api using unittest , getting error as " self.assertJSONEqual(response_content, {"status": 1}) self.fail("First argument is not valid JSON: %r" % raw)" @csrf_exempt @api_view(['POST']) def AdminLoginView(request): if(request.method=="POST"): admin_email = request.data['admin_email'] password = request.data['password'] res = Admin.objects.filter(admin_email=admin_email, password=password).first() if(res): return Response({'status':1},status=status.HTTP_200_OK) return Response({'status':0},status=status.HTTP_200_OK) UnitTest code for testing the above api: def test_admin_login_view(self): req_data = {"admin_email": "test@admin.com", "password": "password"} response = self.client.post('/admin/login/', req_data) self.assertEqual(response.status_code, 200) response_content = response.content.decode("utf-8") self.assertJSONEqual(response_content, {"status": 1}) Please help me on this. -
Django - Order_by a queryset more than once
I want to re-order my queryset after ordering it once. Is it possible? Here is my get_queryset method: def get_queryset(self): id_ordered_logs = BatchLog.objects.filter(batch__user__isnull=False)\ .order_by('-batch_id').distinct('batch_id') return id_ordered_logs I want to order this list by their created_at fields, this is what I want to do: def get_queryset(self): id_ordered_logs = BatchLog.objects.filter(batch__user__isnull=False)\ .order_by('-batch_id').distinct('batch_id') return id_ordered_logs.order_by('-created_at') I'd like to know if this is possible. Thanks and regards.