Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Converting postgres window function with condition into Django ORM
I need help converting following postgres sql into django ORM. with t as ( select ft.student_id , ftd.pending_amt ,row_number() over(partition by student_id order by ftd.created_dt desc) as max_id from fee_transaction ft inner join fee_transaction_detail ftd on ft.id = ftd.fee_transaction_id inner join student s on ft.student_id =s.id where fee_type_id = (select id from fee_type ft2 where id=1) and s.classes_id = 4 and s.faculty_id =3 ) select * from t where max_id=1 and pending_amt > 9000 ; There are 3 tables involved: Student - id,classes_id, faculty_id fee_transaction - id,student_id, fee_transaction_detail - id, pending_amt, created_dt, fee_transaction_id I did go through the django window_function Documentation but couldnt find a concrete example which would help me understand. -
could not connect to server: Connection refused Is the server running on host "database" (172.19.0.3) and accepting TCP/IP connections on port 5432?
I am trying to run Django tests on Gitlab CI but getting this error, Last week it was working perfectly but suddenly I am getting this error during test run django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "database" (172.19.0.3) and accepting TCP/IP connections on port 5432? My gitlab-ci file is like image: docker:latest services: - docker:dind variables: DOCKER_HOST: tcp://docker:2375 DOCKER_DRIVER: overlay2 test: stage: test image: tiangolo/docker-with-compose script: - docker-compose -f docker-compose.yml build - docker-compose run app python3 manage.py test and my docker-compose is like : version: '3' volumes: postgresql_data: services: database: image: postgres:12-alpine environment: - POSTGRES_DB=test - POSTGRES_USER=test - POSTGRES_PASSWORD=123 - POSTGRES_HOST=database - POSTGRES_PORT=5432 volumes: - postgresql_data:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -e \"SHOW DATABASES;\""] interval: 5s timeout: 5s retries: 5 ports: - "5432" restart: on-failure app: container_name: proj hostname: proj build: context: . dockerfile: Dockerfile image: sampleproject command: > bash -c " python3 manage.py migrate && python3 manage.py wait_for_db && gunicorn sampleproject.wsgi:application -c ./gunicorn.py " env_file: .env ports: - "8000:8000" volumes: - .:/srv/app depends_on: - database - redis So why its refusing connection? I don't have any idea as it was working last week :( . Kindly help -
how to connect production settings in django
i have changed this 'django_project.settings' to this 'django_project.settings.production' in wsgi.py , manage.py also in env - 'export django_project.settings.production' but i still get this error (venv) user@ip-172-31-59-68:/var/www/html/web$ python manage.py migrate Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/var/www/html/web/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/var/www/html/web/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/www/html/web/venv/lib/python3.8/site-packages/django/core/management/base.py", line 343, in run_from_argv connections.close_all() File "/var/www/html/web/venv/lib/python3.8/site-packages/django/db/utils.py", line 232, in close_all for alias in self: File "/var/www/html/web/venv/lib/python3.8/site-packages/django/db/utils.py", line 226, in __iter__ return iter(self.databases) File "/var/www/html/web/venv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/var/www/html/web/venv/lib/python3.8/site-packages/django/db/utils.py", line 153, in databases self._databases = settings.DATABASES File "/var/www/html/web/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/var/www/html/web/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/var/www/html/web/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 970, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_project.settings.production'; 'django_project.settings' is not a package how can i change dirrection to read only production.py settings from .base import * SECRET_KEY = os.environ['SECRET_KEY'] DEBUG = False SITE_ID = 1 INTERNAL_IPS = ['127.0.0.1',] ALLOWED_HOSTS = ['127.0.0.1','example.com','www.example.com'] STATIC_ROOT = '/var/www/html/web/blog/static/' MEDIA_ROOT = … -
Django - Filter based on nested sum of related values
I have 3 Django models like this Request is a donation request, RequestItem denotes how many instances of the name item are needed, Donation denotes how many donations have been done for the connected item class Request: pass class RequestItem: name request = ForeignKey(Request) needed = IntegerField() class Donation: item = ForeignKey(RequestItem) donated = IntegerField() I need to filter out the donation requests which aren't still complete The database is ensuring that the sum of the donated items for any RequestItem is never greater than the no of items needed. So my first thought was to get the sum of the needed items, via .annotate(needed=Sum('request_item_set__needed')) and similarly get the total no of donated items, via .annotate(needed=Sum('request_item_set__donation_set__donated')), but as the question suggests, I'm stuck at getting sum of items related to the related items of the entry. -
Django: Avoiding Multiple Queries When Aggregating A Queryset's Model Properties
I have my models.py set up like: class Garage(models.Model): garage_name = models.CharField(max_length=200, null=True, blank=True) class Car(models.Model): car_name = models.CharField(max_length=200, null=True, blank=True) garage = models.ForeignKey(Garage, on_delete=models.CASCADE, related_name="cars", null=True, blank=True) # Returns last service time. @cached_property def last_service(self): last_service = ServiceEvent.objects.filter(car_id=self.id, service_time__lte=timezone.now()).values('service_time').latest('service_time') return last_service.service_time # Returns True If Serviced Since Most Recent Hire. @cached_property def serviced_since_last_hire(self): last_hire = HireEvent.objects.filter(car_id=self.id, end_date__lte=timezone.now()).values('end_date').latest('end_date') if last_service() < timezone.now() and last_service() >= last_hire.end_date: return True else: return False # Returns True If Serviced Since Most Recent Hire. @cached_property def currently_available(self): current_events = HireEvent.objects.filter(car_id=self.id, end_date__gte=timezone.now(), start_date__lte=timezone.now()) if current_events.exists(): return False else: return True class ServiceEvent(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name="service_events") service_time = models.DateTimeField(null=True,blank=True) class HireEvent(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name="hire_events") start_date = models.DateTimeField(null=True,blank=True) end_date = models.DateTimeField(null=True,blank=True) I am using the model properties to reduce code duplication as I use currently_available and serviced_since_last_hire elsewhere. My Views.py attempts to calculate for a given garage 4 aggregate metrics; how many cars are currently serviced how many are currently hired how many are serviced and available how many are not serviced but otherwise available Views.py def garage_test(request, garage_id): car_list = Car.objects.filter(garage_id = garage_id) total_currently_serviced = 0 total_currently_available = 0 total_serviced_and_available = 0 total_not_serviced_and_available = 0 for car in car_list: car_serviced_since_last_hire = car.serviced_since_last_hire … -
request.user on AbstractUser gives AnonymousUser TypeError
Calling request.user on AbstractUser model gives TypeError 'AnonymousUser' object is not iterable. I created an abstract user model as such: class User(AbstractUser): username = models.CharField(blank=True, null=True, max_length=30) email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] def __str__(self): return "{}".format(self.email) I added JSON Web Tokens to my User model. I want to get the details of the current user when I go to a particular URL. To do this, I tried this in views.py: @api_view(['GET']) def getUserProfile(request): user = request.user serializer = UserSerializer(user, many=True) return Response(serializer.data) And this in serialisers.py from django.conf import settings User = settings.AUTH_USER_MODEL class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' Now, when I go to the url where this view is called from, I get TypeError 'AnonymousUser' object is not iterable. I think this is because request.user does not recognise my AbstractUser. This problem occurs even when I am logged in. How do I fix this? -
How to have multiple fields on a line in a django formset
Trying to build a Django formset. I have it working but here is the problem. I want the part of the form which is repeating to have several fields on 1 line - because screen real estate is an issue. The template code I used is: {% extends "base.html" %} {% load static %} {% block title %}{% endblock %} {% block content %} <h2>Program</h2> <hr> <div class="col-md-4"> <form action="" method="post">{% csrf_token %} {{ form.as_p }} <table class="table"> {{ segments.management_form }} {% for form in segments.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle row1 row2 %} formset_row"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% endfor %} </tr> {% endfor %} </table> <input type="submit" value="Save"/> <a href="{% url 'program_update' program.pk %}">back to the list</a> </form> </div> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="{% static 'formset/jquery.formset.js' %}"></script> <script type="text/javascript"> $('.formset_row').formset({ addText: 'add segment', deleteText: 'remove', prefix: 'segment_set' }); </script> … -
Object of type Venta is not JSON serializable - Error when modifying form and saving it in db
I am trying to modify a form, previously everything was fine, but when updating my model with a boolean value I get this error. File "C:\Python\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type Venta is not JSON serializable Trackback: https://pastebin.com/VkChnU9s -
Djanog app quickbooks authorization page from client
need some help to understand how can I have a page in my app in which I ask my clients to authorize my app to have access to my clients quickbooks. I m ok to connect to quickbooks in my app but I add manually clients credentials. I would like to have template in my Django app that handle this. My client will use this template to authorize my app to have access to QBO? any help is kindly needed as I don't know how to do this... thanks -
Passing a Javascript variable to Django view using Ajax
I'm trying to pass a variable from Javascript to a Django view using Ajax. What I got so far is this: template <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <script type="text/javascript"> var Test="SomeValue" // This is the variable that I want to pass $.ajax({ url: '/MyTemplate', type: 'get', data: { test: Test, csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function(data) { alert("Success"); }, failure: function(data) { alert('Error'); } }); </script> In my view: def MyView(request): vrTest = request.GET.get('Test') // Here I tried to use Test, test, data on nothing seems to work print(vrTest) #Here I just want to print the value "SomeValue" But when I print vrTest it the console says None -
'Manager' has no attribute 'get_by_natural_key'
from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, password=None, is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have password") user = self.model( email = self.normalize_email(email) ) user.set_password(password) #change user password user.staff = is_staff user.admin = is_admin user.active = is_active user.save(using=self._db) return user def create_staffuser(self, email, password=None): user = self.create_user( email, password=password, is_staff=True ) return user def create_superuser(self, email, password=None): user = self.create_user( email, password=password, is_staff=True, is_admin=True ) return user class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) full_name = models.CharField(max_length=255, blank=True, null=True) active = models.BooleanField(default=True) #can login staff = models.BooleanField(default=False) #staff user non superuser admin = models.BooleanField(default=False) #superuser timestamp = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' #username #email and password required by default REQUIRED_FIELDS = [] def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active I tried following a video on how to create a custom user model, but when I tried to create a superuser, I got the following error after entering my email: You have 1 unapplied migration(s). Your project may not work properly until you apply … -
Django Rest Framework Serializer - return related field
I have a model with a one-to-one relationship with a main model: class User(models.Model): id = models.BigIntegerField(primary_key=True) username = models.CharField(max_length=100, blank=True) class AggregatedStats(models.Model): user_id = models.ForeignKey('User', on_delete=models.DO_NOTHING, unique=True) followers_30d = models.BigIntegerField(blank=True) I have written the following serializers: class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['id', 'username', 'followers'] class AggregatedStatsSerializer(serializers.HyperlinkedModelSerializer): username = UserSerializer(source='user.username') class Meta: model = AggregatedStats fields = ['followers_30d', 'username'] I am trying to return the username from the User model, but whatever I try to get it, the best I can do is get the hyperlinked related field from user, but not the actual "username" attribute. How would you return this? -
How to add different default values to Foreign Key in Django Models?
I have two models (Article and ArticleContent), in Article, three instances of ArticleContent, which should change only one attribute.I am doing this because each article will have its respective translation. These are my models: class ArticleContent(models.Model): class LANGUAGES(models.TextChoices): ES = 'es', 'Español' EN = 'en', 'English' PT = 'pt', 'Português' language = models.CharField(choices=LANGUAGES.choices, max_length=2) title = models.CharField(max_length=300) body = models.TextField() class Article(models.Model): content_es = models.ForeignKey(ArticleContent, on_delete=models.CASCADE, related_name='article_es') content_en = models.ForeignKey(ArticleContent, on_delete=models.CASCADE, related_name='article_en') content_pt = models.ForeignKey(ArticleContent, on_delete=models.CASCADE, related_name='article_pt') cover_image = models.FileField(upload_to='uploads/') chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE, related_name='articles') What I need to do is something like this, in my Article model: content_es = models.ForeignKey(ArticleContent(language=ArticleContent.LANGUAGES.ES), on_delete=models.CASCADE, related_name='article_es') content_en = models.ForeignKey(ArticleContent(language=ArticleContent.LANGUAGES.EN), on_delete=models.CASCADE, related_name='article_en') If I could do it this way, I could define a default value according to the language. Is there any way to do this? -
It's possible to set the m2m field without saving it in the database/create a database connection/query in Django?
I want to use bulk method to update m2m field, but not works, because .add and .set method create a database connection. These methods take a long time to execute, and the objective of the bulk is precisely to make the insertion be in bulk, and not one at a time Code sample: athletes = Athlete.objects.all() games = Game.objects.all() # objects to update in bulk games_objs_with_m2m = [] for game in games: athlete_related = athletes.get(id=game.athlete_id_ref) game.athlete.add(athlete_related) # here is the problem, .add or .set create a db connection for each instance games_objs_with_m2m.append(game) Game.objects.bulk_update(games_objs_with_m2m, ["athlete"]) Complete code, a script to populate data from csv file: https://pastebin.com/L1pMzBU4 -
Django mobile users
I am currently developing a full-stack solution(web & mobile) using Django restful API as a backend service, my question is how to prevent mobile users from connecting to the web dashboard ?? should I use different endpoints for the mobile version and handle permissions from there ?? what is the best approach you suggest thank you! -
Adding a background task to Django
I don't know if i've chosen a good approach to the problem I'm facing. In fact, there's a very high chance that I'm completely wrong about this. In my Django Application, I need to establish a connection with Twitter API, to continuously get desired tweets. In order to do so, I've written a script using def connect(): response = requests.get( "https://api.twitter.com/2/tweets/search/stream", headers=headers, stream=True, ) for response_line in response.iter_lines(): if response_line: json_response = json.loads(response_line) print(json.dumps(json_response, indent=4, sort_keys=True)) The problem is, I don't know how and where to call this function in Django. Here's what I've found so far: This function blocks the flow of its caller, So it needs to be executed concurrently, whether as a process or a thread. In order to execute such a function, also known as a background task, I need to either use heavy complex options, such as Celery, or light-weight libraries such as DjangoBackgroundTasks. Obviously, I went with DjangoBackgroundTasks and installed it. But now there are a few problems that I can't solve. Firstly, where in the code should I call my connect() function? I've seen people call this in console, but that's not what I want to do, I need to call this, and … -
How can I place two inputs side by side>
I am working with Django Forms and I want to place two input fields side by side but don't have a wrapper on them so is there any way I can do that through css? -
Django Form: copy CheckboxSelectMultiple behavior into a (multi) selectable icon gallery to build a nice menu
Hi I'm trying to achieve this kind of menu design (see image bellow) Basically, the "1" tooltiped image should show a selected state when clicked (like sourrounded)... There will be more images in this row (less than 5) in the future, and they will all have to be selectable (multiple selections), so the underlying form can update everytime a selection is changed This will change the collection of "species" images bellow based on selected categories... So this is exactly the same behavior than a CheckboxSelectMultiple but without the checkbox, ul/li etc, just the icon and "checked" or not state visible... the model: class SpeciesCat(models.Model): category = models.CharField(max_length=255, unique=True, null=False) logo = models.ImageField(blank=True, null=True) def __str__(self): return (self.category) class Meta: ordering = ['category'] class Species(models.Model): category = models.ForeignKey(to=SpeciesCat, null=False, on_delete=models.DO_NOTHING) common_name = models.CharField(max_length=255, unique=True, null=False) logo = models.ImageField(blank=True, null=True) def __str__(self): return (self.common_name) class Meta: ordering = ['common_name'] the form: class CategoriesSelectForm(forms.Form): categories = forms.ModelMultipleChoiceField(queryset=SpeciesCat.objects.all(), widget=forms.SelectMultiple(attrs={"onchange": "this.form.submit()"}), required=False) the view: def index_view(request): species = [] if request.method == "POST": if "categories" in request.POST: if categories_form.is_valid(): categories = categories_form.cleaned_data["categories"] species = Species.objects.filter(category__in=categories) context = {'species_list': species} return render(request, 'home/home.html', context) the template: <div id="left_menu_floatbar"> <div class="menu_row"> <form name="categories" action="/" method="post">{% csrf_token %} … -
Django - request.is_secure always returns False
I'm running a Django project on a DigitalOcean VPS using Nginx and Gunicorn. I made sure that i'm using HTTPS, but for some reason using request.is_secure() always returns False, and request.scheme returns HTTP, even though i made sure it's VPS. What could be the reason for that? Here is my nginx config: server { listen 80; server_name MY.SERVER.com; location / { include proxy_params; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/var/www/proj/myproj.sock; } } And i also made sure to add to my Django settings SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https'). Any advice is appreciated -
How to add Trailing slash (/) in url of sitemap Django?
I want to add (/) in site map of Django. I have used following code to generate sitemap in django my url.py is from django.contrib.sitemaps.views import sitemap from myApp.sitemaps import staticSitemap , mySitemap sitemaps = { 'staticSitemap':staticSitemap, 'mySitemap':mySitemap } urlpatterns = [ path('admin/', admin.site.urls), path('sitemap.xml', sitemap, {'sitemaps': sitemaps} ), path('<slug:slug>/',apps.switcher, name='calc_detail'), ] my sitemap file is like below from django.contrib.sitemaps import Sitemap from django.shortcuts import reverse from .models import SingleCalculator class staticSitemap(Sitemap): changefreq = "weekly" priority = 0.9 def items(self): return ['home','about','contact','privacy'] def location(self, item): return reverse(item) class mySitemap(Sitemap): changefreq = "weekly" priority = 0.7 def items(self): return SingleCalculator.objects.all() def lastmod(self,obj): return obj.lastmod Sitemap is generating now like following URL in loc <loc>https://sitename.com/absolute-difference-calculator</loc> I want (/) after the end of url. How can I do this? -
Django custom authentication with a mysql db
Im using Django without models and an external authentication source (mysql db). Im searching now for a way to authenticate and login users with that mysql db. It should also be possible to use user.is_authenticated in templates. Im not sure if that's only possible if I replicate the mysql db to Django's Usersmodels. But I think that would be hard to maintain. Like updating both on a passwordreset and so on. In a nutshell: Is there a way to authenticate Users in Django externally, and have the advantage of user.is_authenticated and @login_required. -
Django Comment Section Issue
im new to django , im trying to build a blog by my self but i sucked on comment section 1- i dont know to make comment form under the blog post without going to a new page using Class Based View 2- i could add comment section and the logic that i need using function view but im facing a problem . when i try to post a comment with a user it says You are trying to change the nullable field 'name' on comment to non-nullable without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Ignore for now, and let me handle existing rows with NULL myself (e.g. because you added a RunPython or RunSQL operation to handle NULL values in a previous data migration) Quit, and let me add a default in models.py if i put null=True on name model it will show the comment without the author class Comment(models.Model): post = models.ForeignKey(Postrelated_name='comments', on_delete=models.CASCADE) name = models.ForeignKey(User, related_name='author', on_delete=models.CASCADE) comment = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return … -
how to get id of an object from url of page django
i have created a list in which it shows the name of all groups present when you click it redirect to another page with group id, when i create a post i need to specify which group it is, i am getting the id in url of page but i have no idea how to define group object with that url, views def create(request): if request.method == "POST": name = request.user author = request.user message = request.POST['message'] message = comments(user=author,message=message,name=name,group_id=2) message.save() return HttpResponse('') instead of group_id=2 or hardcode it , can i automatically take the id from url of the page like we do in request.user models class group(models.Model): group_name = models.CharField(max_length=100) group_user = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return f'{self.id} group' class comments(models.Model): userId = models.AutoField(primary_key=True) name = models.CharField(max_length=100) group = models.ForeignKey(group,on_delete=models.CASCADE,null=True) user = models.ForeignKey(User,on_delete=models.CASCADE) message = models.TextField() date = models.TimeField(auto_now_add=True) def __str__(self): return f'{self.user} comments' i have been trying day and night and couldnt solve, all the genius programmers out there pls give me a solution -
How can I download CSV file from the URL and use that data in my own backend? (Node.js or Python)
I have link which when I open in the browser it downloads the CSV file with the data. How can I use a backend controller that will open that link and use that downloaded CSV for fetching that data? I am planning to make it either with Node.js or Python -
How to limit top N of each group in Django ORM by using Postgres Window functions or Lateral Joins?
I have following Post, Category & PostScore Model. class Post(models.Model): category = models.ForeignKey('Category', on_delete=models.SET_NULL, related_name='category_posts', limit_choices_to={'parent_category': None}, blank=True, null=True) status = models.CharField(max_length=100, choices=STATUS_CHOICES, default='draft') deleted_at = models.DateTimeField(null=True, blank=True) ... ... class Category(models.Model): title = models.CharField(max_length=100) parent_category = models.ForeignKey('self', on_delete=models.SET_NULL, related_name='sub_categories', null=True, blank=True, limit_choices_to={'parent_category': None}) ... ... class PostScore(models.Model): post = models.OneToOneField(Post, on_delete=models.CASCADE, related_name='post_score') total_score = models.DecimalField(max_digits=8, decimal_places=5, default=0) ... ... So what i want is to write a query which returns N number of posts (Posts) of each distinct category (Category) sorted by post score (denoted by total_score column in PostScore model) in descending manner. So that i have atmost N records of each category with highest post score. So i can achieve the above mentioned thing by the following raw query which gives me top 10 posts having highest score of each category : SELECT * FROM ( SELECT *, RANK() OVER (PARTITION BY "post"."category_id" ORDER BY "postscore"."total_score" DESC) AS "rank" FROM "post" LEFT OUTER JOIN "postscore" ON ("post"."id" = "postscore"."post_id") WHERE ("post"."deleted_at" IS NULL AND "post"."status" = 'accepted') ORDER BY "postscore"."total_score" DESC ) final_posts WHERE rank <= 10 What i have achieved so far using Django ORM: >>> from django.db.models.expressions import Window >>> from django.db.models.functions import Rank >>> …