Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make simple filtration with django-filter
I faced with a problem. I have a simple drf project with car-entrance permits application. views.py ` class PermitViewSet(ModelViewSet): queryset = Permit.objects.filter() serializer_class = PermitSerializer filter_backends = [DjangoFilterBackend] filter_fields = ['car_number'] serializers.py ` class PermitSerializer(serializers.ModelSerializer): class Meta: model = Permit fields = ['car_number', 'is_active'] models.py ` class Permit(models.Model): car_number = models.CharField(max_length=15) customer = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) urls.py router = SimpleRouter() router.register(r'permit', PermitViewSet) urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += router.urls ` i type in my browser http://127.0.0.1:8000/api/v1/permits/?car_number=555 and i recieve full list of cars ` [{"car_number":"555","is_active":true},{"car_number":"666","is_active":true},{"car_number":"777","is_active":true}] ` It doesn't work, what's the problem? -
Supervisor shutsdown when I have multiple services in the .conf file
I have a Linux server running ubuntu 22.10 with digital ocean where I plan to host multiple virtualenv to run isolated Django applications. Using gunicorn to serve the application and nginx as the reverse proxy. The supervisor to control the processes. I started with one django application and everything was working fine. on adding the second .conf file for the second application, the supervisor shuts down and subsequent supervisorctl commands return this error unix:///var/run/supervisor.sock refused connection this is my supervisor configuration [program:brotherstech] command=/home/webapps/brotherstech/bin/gunicorn_start user=ops autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/webapps/brotherstech/logs/gunicorn-error.log [program:officebook] command=/home/webapps/officebook/bin/gunicorn_start user=ops autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/webapps/officebook/logs/gunicorn-error.log -
Django Graphene hiding a model field (or return null) based on user preference in ManyToMany
assume we have the following Django Models: class Person(models.Model): name = models.CharField(max_length=255) personal_field = models.CharField(max_length=255) class Group(models.Model): name = models.CharField(max_length=255) participants = models.ManyToManyField( "Person", through="GroupPersonOption", through_fields=('group', 'person') ) class GroupPersonOption(models.Model): person = models.ForeignKey("Person", on_delete=models.CASCADE) event = models.ForeignKey("Event", on_delete=models.CASCADE) hide_personal_field = models.BooleanField(default=False) Example: Based on the group a user is in, they can choose to hide their personal_field, so that instead of its regular value, None or Null is returned. The Person can set this in the ManyToMany Model called GroupPersonOption Where it gets tricky: How do I change its value to None in my DjangoObjectTypes? When I try to add a resolve function for the personal_field in PersonObjectType, I don't know if the user wanted to hide this info. Graphene Code: { peopleByGroup(name: "DjangoIsAwesome") { person { name personal_field } } } I have waited a few days in the Django Subreddit but the only solution one person came up with was just to ignore setting the personal_field to None based on some value and then hide it in the frontend, however that is not an acceptable solution, as this would expose user data. I have also tried adding a resolve_person function to the PersonEventOptionType, but that broke a lot … -
How to subtract contents of IntegerField of one table from another in Django?
How it works: When I add a product to the Bouquet table, in the CompositionOfTheBouquetInline class, I can select an object from the Flower table and select the number of flowers. For example, there is a "Rose" flower in the Flower table, stock = 10 there is a bouquet "Bouquet of roses" in the Bouquet table, stock = 1 select the "Rose" flower in the amount of 5 and save, in the CompositionOfTheBouquet table What is going to happen: flower "Rose" is now stock = 5, in the Flower table Formula: Flower.stock = Flower.stock - (CompositionOfTheBouquet.count * Bouquet.stock) models.py class Flower(models.Model): title = models.CharField(max_length=100) stock = models.PositiveIntegerField(default=0) class Bouquet(models.Model): title = models.CharField(max_length=150) stock = models.PositiveIntegerField(default=0) class CompositionOfTheBouquet(models.Model): flower = models.ForeignKey( Flower, on_delete=models.PROTECT ) bouquet = models.ForeignKey( Bouquet, on_delete=models.PROTECT ) count = models.PositiveIntegerField(default=0) admin.py from .models import Flower, Bouquet, CompositionOfTheBouquet class CompositionOfTheBouquetInline(admin.TabularInline): model = CompositionOfTheBouquet @admin.register(Flower) class Flower(admin.ModelAdmin): pass @admin.register(Bouquet) class Bouquet(admin.ModelAdmin): inlines = [CompositionOfTheBouquetInline, ] What you need to do: When adding a flower and its quantity, you need to remove this number of flowers and save it in the Flower table, stock column. Important: calculations should take place when adding a Bouquet through the admin panel -
Django media 'image.url' showing the image path instead of the actual image
here's the HTML: {{player.image.url}} and this is what it shows up: the view: def homepage(request): thePlayer = Player.objects.get(name="Hamada") return render(request, 'homepage.html', {'player': thePlayer}) settings.py: MEDIA_ROOT = path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' image field in the model: image = models.ImageField(default="images.png") project urls.py: from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('mainApp.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) app urls.py: from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.homepage, name="homepage") ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
inserting a django form with javascript
what I am trying to do is fairly simple: I want to add {{ form }} to a table cell with javascript this what I have but it only works for labels: function showOrHideReconciliationTable() { var checkBox = document.getElementById("edit-inventory-reconciliation"); if (checkBox.checked == true) { var table = document.getElementById("main-table"); var row = table.insertRow(7); row.classList.add("warehouse-row"); row.setAttribute('id','table-toogle'); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); var cell3 = row.insertCell(2); cell1.innerHTML = "{{ form }}"; cell2.innerHTML = "NEW CELL2"; cell3.innerHTML = "NEW CELL3"; } else { var table = document.getElementById("main-table"); var row = table.deleteRow(7); } any help would be appreciated (it's probably something simple or you cannot do it this way) Thanks! -
Filter available blocks for StreamField in Wagtail's Editor Interface
I have the following StructBlock subclasses and Page subclass class TestimonialBlock(blocks.StructBlock): class Review(blocks.StructBlock): text = blocks.TextBlock(label=_("Text")) author = blocks.TextBlock(label=_("Author")) link = blocks.URLBlock(required=False, label=_("Author link")) class Meta: icon = "openquote" label = _("Testimonial") title = blocks.TextBlock(required=False, label=_("Title")) review_list = blocks.ListBlock(Review(), label=_("Review(s)")) class TeamBlock(blocks.StructBlock): class Member(blocks.StructBlock): name = blocks.TextBlock(label=_("Name")) role = blocks.TextBlock(label=_("Role")) photo = ImageChooserBlock(label=_("Photo")) link = blocks.URLBlock(required=False, label=_("Profile link")) class Meta: icon = "group" label = _("Team") title = blocks.TextBlock(required=False, label=_("Title")) member_list = blocks.ListBlock(Member(), label=_("Member(s)")) class RPTeamBlock(blocks.StructBlock): class UpMembers(blocks.StructBlock): photo = ImageChooserBlock(label=_("Photo")) link = blocks.URLBlock(required=False, label=_("Profile link")) class Meta: icon = "group" label = _("RPMember") class DownMembers(blocks.StructBlock): photo = ImageChooserBlock(label=_("Photo")) link = blocks.URLBlock(required=False, label=_("Profile link")) class Meta: icon = "group" label = _("RPMember") class Meta: icon = "group" label = _("Team") title = blocks.TextBlock(required=False, label=_("Title")) up_member_list = blocks.ListBlock(UpMembers(), label=_("Member(s) top")) down_member_list = blocks.ListBlock(DownMembers(), label=_("Member(s) down")) class LandingPage(Page): THEMES = [("transitive", "Transitive"), ("rp", "RP")] # WEBSITE IDENTITY website_theme = models.CharField( blank=False, null=False, max_length=32, choices=THEMES, default=THEMES[0][0], verbose_name=_("Theme"), ) website_logo = models.ForeignKey( "wagtailimages.Image", blank=True, null=True, on_delete=models.SET_NULL, verbose_name=_("Logo"), related_name="website_logo", ) # WEBSITE CONTENT body = StreamField( [ ("testimonial", TestimonialBlock()), ("team", TeamBlock()), ("rpteam", RPTeamBlock()), ], blank = True, null = True, use_json_field = True ) content_panels = Page.content_panels + [ MultiFieldPanel( [ FieldPanel("website_theme", widget=forms.Select), FieldPanel("website_logo"), ], … -
How to get annotated attributes in a template from a DetailView?
I'm working on a small e-commerce. For a model 'Product' I keep track of the stock using a Custom Manager and a method called Products.objects.with_stock() that uses annotations (I'm required to do so, there's no way I can add a stock attribute in Product) In a ListView of all the products, it's pretty straightforward to add the stock, to access it from a template: # app/views.py class ProductListView(ListView): ... def get_stock(self, obj): return obj.stock def get_queryset(self): return super().get_queryset().with_stock() And then in the template I just call it: <!-- templates/home.html--> {% for product in products %} <p> Stock: {{product.stock}} <p> {% endfor %} How do I perform something similar for a DetailView? Given that a DetailView gets a particular object instance, where or how do I run something similar to what I did in the ListView? Where do I run that query method that affects all objects as a whole, so that then I can access it in the same way from the template? -
How to use whitenoise with digitalochen space?
Attempted access to '/img/apple-touch-icon.png' denied. , django - digitalocean - spaces what is the riget way to connect django with digitalocean spaces this is my code from storages.backends.s3boto3 import S3Boto3Storage class StaticRootS3Boto3Storage(S3Boto3Storage): location = 'static' class MediaRootS3Boto3Storage(S3Boto3Storage): location = 'media' import os AWS_ACCESS_KEY_ID="----" AWS_SECRET_ACCESS_KEY="---" AWS_STORAGE_BUCKET_NAME="---" AWS_S3_ENDPOINT_URL="---" AWS_S3_OBJECT_PARAMETERS = { "CacheControl": "max-age=86400", } AWS_LOCATION = "----" DEFAULT_FILE_STORAGE = "----.cdn.backends.MediaRootS3Boto3Storage" STATICFILES_STORAGE = "----.cdn.backends.StaticRootS3Boto3Storage" DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') MEDIA_URL = '/images/' and i got this erorr when i run my server -
How to reduce called paramets in methods?
I have a class and in that class I have a method that calls multiple methods in it. But the problem I am facing now is that when the method with the multiple methods in it duplicate parameter has. And so when I am calling the method with the multiple methods in it, it returns a empty list:[]. So this is the method with the multiple methods in it: def show_extracted_data_from_file(self, file_name): self.extractingText.extract_text_from_image(file_name) total_fruit = self.filter_verdi_total_number_fruit() fruit_name = self.filter_verdi_fruit_name() fruit_total_cost = self.filter_verdi_total_fruit_cost(file_name) return "\n".join("{} \t {} \t {}".format(a, b, c) for a, b, c in zip(total_fruit, fruit_name, fruit_total_cost)) and this is the method: filter_verdi_total_fruit_cost: def filter_verdi_total_fruit_cost(self, file_name): locale.setlocale(locale.LC_ALL, locale='Dutch') self.extractingText.extract_text_from_image(file_name) return [ locale.atof(items[-1]) for items in ( token.split() for token in file_name.split('\n') ) if len(items) > 2 and items[1] in self.extractingText.list_fruit ] this method returns the following data: [123.2, 2772.0, 46.2, 577.5, 69.3, 3488.16, 137.5, 500.0, 1000.0, 2000.0, 1000.0, 381.25] You see that I am calling two times file_name. and so when I calling the method show_extracted_data_from_file in the views.py: if uploadfile.image.path.endswith('.pdf'): content = filter_text.show_extracted_data_from_file(uploadfile.image.path) print(content) it produces a empty list: [] Question: how can reduce the parameter file_name so that it return the correct results? -
Multiple model instance django rest-framework
I was trying to find a way to create multiple objects with one API request in a django-rest based API. I found many answers to that and I came up with overriding ViewSet.get_serializer method as follows def get_serializer(self, *args, **kwargs): data = kwargs.get('data', None) if data: kwargs['many'] = isinstance(data, list) return super().get_serializer(*args, **kwargs) I also overrided serializer.to_representation in order to add some useful data to representation. Problem is that doing that when I create a single object per request everything's fine, but when I try to create multiple objects I get errors in serializer.to_representation method. I tried to debug the error and seems that when serializer is initialized with many=True instance passed to serializer.to_representation is a OrderedDict rather than the actual instance, so I cannot access properties of the instance like related fields, etc. def to_representation(self, instance): if self.context['request'].method == 'POST': print(type(representation), type(instance)) return super().to_representation(instance) This will output <class 'collections.OrderedDict'> <class 'main.models.Expenditure'> as expected for single object post request but for multiple object (which still are correctly created) requests output is more complex. <class 'collections.OrderedDict'> <class 'main.models.Expenditure'> <class 'collections.OrderedDict'> <class 'main.models.Expenditure'> <class 'collections.OrderedDict'> <class 'collections.OrderedDict'> <class 'collections.OrderedDict'> <class 'collections.OrderedDict'> in this example I tried to create two objects. The second … -
Django async view - how do I know its running async?
I can create an async view and inquire as to whether the method thinks it's a coroutine, and it is. However, looking at the stack it looks like my view is being called by asgiref's SyncToAsync. I am using Gunicorn with Uvicorn worker and an asgi.py script that starts with: from channels.routing import get_default_application channel_layer = get_default_application Plus, I am trying to discover if any of my middleware is running sync or even with a (forced) sync middleware I am not hitting (logger.debug('Synchronous %s adapted.', name)) Makes no sense. -
my django site is not opening under jammu and kashmir area in airtel network , it is on digital ocean
my site is not opening under Jammu and Kashmir area in India in Airtel network.In other network its opening.In Airtel every other site is opening , only my site not opening . -
Can't start project file Django using django-admin startproject mysite
so I am learning how to work with Django and for some reason I always get this error: I installed Django with py -m pip install Django==2.0.4 and then I updated it with command. It always create empty folder without any file inside of it. I have no idea why is this happening. Any help would be blessing. -
Difference between hosting Postgresql database on Railway or on AWS/Azure
I'm working on a django application I need to put online. For now I've only been working on personal projects that I never deployed. Searching for the best solutions, I found that Railway seems to be the easiest choice, and that I can even host the app and the database on it (and even the static files!). I don't know so much about databases, that's why I wonder if there are differences between hosting everything (the code + the database) on Railway or hosting the code on Railway, and connect it to a database hosted on AWS, Azure etc... It seems "too easy" for me to be possible to do that. Maybe the databases on Railway are great only for small usages ? I didn't find anything on the internet comparing those services and talking about the possible limits of Railway. Thanks a lot in advance for your help. -
Forbidden (CSRF cookie not set.): /auth for obtaining_auth_token
I am trying to get an auth token for the client (OrderClient.py). This keeps failing with Forbidden (CSRF cookie not set.): /auth. Here is my views from rest_framework.decorators import api_view,permission_classes,authentication_classes from rest_framework.response import Response from .serializers import OrderSerial from rest_framework.authentication import SessionAuthentication, TokenAuthentication from rest_framework.permissions import IsAuthenticated @api_view(['POST']) @authentication_classes([SessionAuthentication, TokenAuthentication]) @permission_classes([IsAuthenticated]) def make_order(request,*args,**kwargs): user1=request.user serializer = OrderSerial(user=user1) print(serializer.is_valid()) data={'abc':'cde'} return Response(data=data) Here is my urls.py from django.urls import path from Products.views import home_view,Phone_input_view,Phone_list_view,Phone_edit_view from Products.api.views import make_order from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ path('',home_view), path('auth/', obtain_auth_token), path('createPhone/',Phone_input_view), path('viewPhoneList/',Phone_list_view), path('edit/<int:id>',Phone_edit_view), path('order/', make_order) ] I have added the 'rest_framework.authtoken' to installed apps in settings. I was expecting to retrieve the token and successfully sign in -
Django function view rewriting to Class View UpdateView problem with Multiple Forms
Im trying to rewrite my whole app from function views to class views. Right now Im struggle with UpdateView I know that it can only accept one parameter of FORM. But I wonder after rewriting the code from topics (like mine) how to do it correctly and make it works. And Does it make sense to interfere with the intentions of the Django Developers? Or just leave this view as a view function? This how its looks right now views.py @login_required def edit_user_info(request): user = get_object_or_404(User, id=request.user.id) user_profile = get_object_or_404(UserProfile, profile=request.user) if request.method == "POST": user_form = UserForm(request.POST, instance=user) profile_form = UserProfileForm(request.POST, instance=user_profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, "Your profile is updated successfully") return redirect(to="profile") else: user_form = UserForm(instance=user) profile_form = UserProfileForm(instance=user_profile) context = { "user_form": user_form, "profile_form": profile_form, } return render(request, "web/update_user_info.html", context) forms.py class UserForm(forms.ModelForm): email = forms.EmailField(required=False,label="Updated email address if different", widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = User fields = ("email",) class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ("about_user","user_photo",) and what I would like to make with UpdateView or other class View MultiModelFormView, TemplateView Also, I would like to leave the auto filled with forms, with user data class EditUserView(MultiModelFormView): form_classes = { … -
How can i upload videos using django rest api with cloudinary
Well im doing a project in django rest for backend and react as front end, i want to do 2 post modals one for video and another for images, the image is fine but the video dont work, when i set filefield i get an error saying is not a valid image file, also tried to do with cloudinary where all my images are stored, i cant figure it out how to do it, tried countless times but with no avail the video post model ` class VideoPost(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.TextField(max_length=100, blank=True) content = models.TextField(blank=True) video = models.FileField(upload_to='images/', blank=True) post_categorys_filter = models.CharField( max_length=50, choices=post_categorys, default='normal' ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-created_at'] def __str__(self): return f'{self.id} {self.title}' the serializer class VideoPostSerializer(serializers.ModelSerializer): author = serializers.ReadOnlyField(source='author.username') is_author = serializers.SerializerMethodField() profile_id = serializers.ReadOnlyField(source='author.profile.id') profile_image = serializers.ReadOnlyField( source='author.profile.image.url') comments_count = serializers.ReadOnlyField() likes_count = serializers.ReadOnlyField() dislikes_count = serializers.ReadOnlyField() video = serializers.FileField() def get_is_author(self, obj): request = self.context['request'] return request.user == obj.author class Meta: model = VideoPost fields = [ 'id', 'author', 'is_author', 'profile_id', 'profile_image', 'content', 'created_at', 'updated_at', 'post_categorys_filter', 'video', 'likes_count', 'comments_count', 'dislikes_count' ] ` -
Trying to find a good example to create a html button in django to run a python function and display result
I've trying for a while now to learn django mostly for my own curiosity. My current goal is to have an button on screen that when pressed does some simple python function at first. Something like display a string value or a random number on the screen. I've found some examples but they're not helping my understanding of the problem. Most examples have been building like buttons or similar. I've tried looking into ajax calls for python but I can't seem to find writeups that help me with the basics and any video tutorials I find on this topic there is a language barrier which is not helping me learn. Sorry for asking probably a basic question. -
Why data not loading from db?
There are model: class Employee(models.Model): name = models.CharField(max_length=100) position = models.CharField(max_length=100) hired_at = models.DateField(auto_now=True) salary = models.DecimalField(max_digits = 9, decimal_places= 2) boss = models.ForeignKey('self', null=True,blank=True, on_delete=models.CASCADE) def __str__(self): return f'<{self.pk}> {self.name} - {self.position}' There are view: class EmployeeView(ListView): model = Employee context_object_name = 'employees' template_name = 'employees-list.html' def get_queryset(self): return Employee.objects.all() I have 5 people in my db, but then i try to load my url from pattern: path('', EmployeeView.as_view()), I got this in my console: "GET /employees/ HTTP/1.1" 200 55 And <> - on web page, why data not loading? -
i want use the value of incremated 'i' from second file
this is first file that contains value of i class Qury: i=0 def makedb(self): self.making_key() def making_key(self): global i for t in range(12): self.i+=1 def making_key2(self): global i for t in range(14): self.i+=1 print(self.i) first file that making object from django.core.management.base import BaseCommand from Qurys import Qury Q=Qury() print(Q.i) class Command(BaseCommand): global Q def handle(self,*args,**kwargs): Q.makedb() print(Q.i) second file the real problem is here from django.core.management.base import BaseCommand from home.management.commands.make_db import Q class Command(BaseCommand): def handle(self,*args, **kwargs): Q.making_key2() this is django project i want to user the increment value of i to add in user in database (cassandra) i want make a command that can add user but start from increment value of i -
How to turn ROM objects into hashes when using a raw query with a join, and get only a subset of DB fields?
I have a query with the following format: query_str = """ SELECT A.id, A.location::bytea, A.author_id, B.username FROM A JOIN B ON A.author_id = B.id """ for p in Database.objects.raw(query_str): # how to get the hashes here? How can I get hashes here that only contain the field that are SELECTed in the raw query? I tried model_to_dict but that returns all fields and only fields from table A. -
Contact() got an unexpected keyword argument 'listing'
`from django.shortcuts import render, redirect from .models import Contact from django.contrib import messages Create your views here. def Contact(request): if request.method == 'POST': listing_id = request.POST['listing_id'] listing = request.POST['listing'] name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] message = request.POST['message'] user_id = request.POST['user_id'] realtor_email = request.POST['realtor_email'] contact.save() messages.success( request, 'Your request has been submitted, a realtor will get back to you soon') rn redirect('listings'+listing_id) ` i'm trying to save the data from database. but give the error TypeError. -
How To Update Value From Views ? and How to Parse Id to get_success_url for DetailView ? In Django
How To Update Value From Views ? And Parse Id to DetailView ? Problem Update Value I Try to write query.attendance and query.status, to get data from database. but the error said "'QuerySet' object has no attribute 'attendance' / 'status'" Problem Parse Id I dont now how to parse this id to get_success_url 1. home/views.py class HomeView(FormView): template_name = 'home/index.html' form_class = TicketForm def form_valid(self, form): getId = form.cleaned_data['nomor_ticket'] query = Graduates.objects.filter(ticket_id=getId) if query: **#FIRST ERROR (attendance and status has no attribute)** print(query.attendance == timezone.now()) print(query.status == True) **#FIRST END ERROR** print('ticket available') else: print('no ticket not found ') print(query) return super().form_valid(form) def get_success_url(self): return reverse('attendance:index' + how to get id ?) 2. attendance/models.py class StudyProgram(models.Model): study_program_id = models.IntegerField() name = models.CharField(max_length=100) def __str__(self): return self.name class Graduates(models.Model): ticket_id = models.CharField(primary_key=True, max_length=16, unique=True, default=custom_id) graduate_number = models.IntegerField() student_id = models.IntegerField() full_name = models.CharField(max_length=100) study_program = models.ForeignKey(StudyProgram, on_delete=models.CASCADE) attendance = models.DateTimeField(blank=True, null=True, editable=False) status = models.BooleanField(default=False) 3. attendance/views.py class Attendance(DetailView): model = Graduates template_name = "attendance/index.html" 4. attendance/urls.py from django.urls import path from . import views app_name = 'attendance' urlpatterns = [ path('<pk>/', views.Attendance.as_view(), name='index'), ] -
Django REST Framework pagination changing model ordering
For some reason when I run paginate_queryset(queryset) the ordering changes, and is not the order I want. I have the model: class MyModel(models.Model): name = models.CharField(max_length=100) history_date = models.DateTimeField() class Meta: managed = False db_table = 'myapp_historicalmymodel' ordering = ("-history_date",) With the ordering field set. Then I have an extra action in a ViewSet: class MyModelViewSet(viewsets.ModelViewSet): serializer_class = MyModelSerializer permission_classes = [permissions.IsAuthenticated] queryset = MyModel.objects.all() @action(detail=False, methods=['get'], url_path='history', url_name='history') def history(self, request): items = HistoricalMyModel.objects.all() print(items) # FIRST PRINT page = self.paginate_queryset(items) print(page) # SECOND PRINT if page is not None: serializer = HistoricalMyModelSerializer(page, many=True, context={'request': request}) return self.get_paginated_response(serializer.data) serializer = HistoricalMyModelSerializer(items, many=True) return Response(serializer.data) The first print prints out items in the configured order, using ordering = ("-history_date",), like: <QuerySet [<HistoricalMyModel: HistoricalMyModel object (4)>, <HistoricalMyModel: HistoricalMyModel object (3)>, <HistoricalMyModel: HistoricalMyModel object (2)>, <HistoricalMyModel: HistoricalMyModel object (1)>]> There you can see the order 4,3,2,1. But the second print prints items out in some default Postgres order it seems: [<HistoricalMyModel: HistoricalMyModel object (3)>, <HistoricalMyModel: HistoricalMyModel object (4)>, <HistoricalMyModel: HistoricalMyModel object (1)>, <HistoricalMyModel: HistoricalMyModel object (2)>] There you can see the order 3,4,1,2. Why is it changing the order of items after running self.paginate_queryset(items)?