Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django API: How to get all objects that match certain value in UUID field
when trying to query objects on their foreignkey field, I dont manage to get any details. The company ID is and uuid (uuid4) field. I have a Model called "contacts": class Contact(models.Model): firstname = models.CharField(max_length=35) lastname = models.CharField(max_length=35) company = models.ForeignKey(Company, on_delete=models.CASCADE) I want to get all Contacts, that work for the same company. Therefore I have created a ListAPIView whitin views.py Views.py class ContactViewSet(viewsets.ModelViewSet): queryset = Contact.objects.all() serializer_class = ContactSerializer class CompanyContactsListView(generics.ListAPIView): serializer_class = ContactSerializer def get_queryset(self): company = self.kwargs['company'] return Contact.objects.filter(company=company) And to get a URL I added the path in urls.py urlpatterns = [ path('', include(router.urls)), path('contacts/<uuid:company>/', CompanyContactsListView.as_view(), name='contacts') ] Problem is, that when i try to go for that path and enter an UUID of an company that exists and has related contacts, I get the following error HTTP 404 Not Found Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Not found." } Is it possible, that my URL is wrong and therefore cant query the ListAPIView? Because I want result like that: [ { "id": 1, "firstname": "Joshuah", "lastname": "Bankhurst", "company": "e871c47b-9b91-4cf9-94a6-e8135510c11d" }, { "id": 2, "firstname": "Clayborn", "lastname": "Sylett", "company": "e871c47b-9b91-4cf9-94a6-e8135510c11d" } ] Thanks in advance! -
Django : Quering data from related models
So i use Django 3.2.7 and i would like to query all orders from a customer. Models.py class Order(models.Model): STATUS=( ('Pending','Pending'), ('Out for Delivery','Out for delivery'), ('Delivered','Delivered'), ) customer = models.ForeignKey(Customer,null=True, on_delete=models.SET_NULL) product = models.ForeignKey(Product,null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=200, null=True, choices=STATUS) Views.py def customer(request,pk): customer = Customer.objects.get(id=pk) orders = customer.order_set.all() my_context={ 'customer':customer, 'orders':orders } return render(request, 'accounts/customer.html', context=my_context) Urls.py path('customer/<str:pk>/', views.customer), Template {% for order in orders %} <tr> <td> {order.product} </td> <td> {order.product.category} </td> <td> {order.date_created} </td> <td> {order.status} </td> <td><a href="">Update</a></td> <td><a href="">Delete</a></td> </tr> {% endfor %} My problem is that instead of printing the actual data on the template is prints the query data. I think the problem is at orders = customer.order_set.all(). What im doing wrong? -
Turning RabbitMQ off makes Django to freeze
I have this class in my project: class CreateReportConsumer(AsyncJsonWebsocketConsumer): async def connect(self): if self.scope['user'].is_authenticated: await self.accept() else: await self.close(401) async def disconnect(self, code): await self.close(code) async def receive_json(self, content, **kwargs): task_id = content.get('task_id') if task_id: result = AsyncResult(task_id) start = datetime.now() while not result.ready(): await sleep(1) if datetime.now() - start > timedelta(seconds=60 * 5): await self.send_json(self.construct_answer([False, 'Connection timed out'])) await self.close(500) break else: if result.state == 'SUCCESS': if len(result.result) == 2: await self.send_json(self.construct_answer(result.result)) await self.close(200) else: await self.close(500) else: await self.send_json(result.result) await self.close(500) else: await self.close(500) def construct_answer(self, data): return {'success': data[0], 'message': data[1]} It gets result from Celery task, when someone using this. But if I turn RabbitMQ off (I am using docker container for that), it freezes. Is there any way of avoiding that? I have tried using pika, but with the same result. Thanks everybody. -
module 'keras.optimizers' has no attribute 'Adam'
when i run this python FlappyBird_AI.py -m train this error occured AttributeError: module 'keras.optimizers' has no attribute 'Adam' -
ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'leads.user', but app 'leads' doesn't provide model 'user'
i'm making crm when i type python manage.py migrate i got this error: ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'leads.user', but app 'leads' doesn't provide model 'user'. if you wan't more detail you can tell me i'm little bit beginner here's settings.py AUTH_USER_MODEL = 'leads.User' here's models.py from django.db import models from django.contrib.auth.models import User, AbstractUser class User(AbstractUser): pass class Lead(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) phone = models.BooleanField(default=False) agent = models.ForeignKey("Agent",on_delete=models.CASCADE, null=True) class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) -
Access data after the Question mark(?) [closed]
Suppose I have a URL like this given below and I want to access the quiz_id parameter. http://localhost:3000/attempt/?quiz_id=6 How do I make this possible using Axios and in Django? -
Question regarding to Reactjs and Django, the use of serializer in django-rest-framework
I have a question regarding to the serializer from Django-rest-framework and Reactjs. My question is that can the serializer work itself without the django model? since I don't need to save anything in database. I just want to do post request to backend, and it will take the data and run the ML model, and show the result back to frontend. After that the record will be cleared. Will it be possible to do so without using model? Can I only save serializer instance and give a get request to show it in the frontend? Thank you! -
how to deploy a django project with apache and basic authentication?
I've finished a django project and i want to deploy that on ubuntu server with public ip. but i don't want this project visible to public and i want to set an basic authentication for that. i thought if i set apache basic authentication for a specefic port (for example 8000) and then run django on this port, everything will be ok, but i faced the Listening port for another service (apache) problem and i can't run django on this port. how i can solve this problem? here is my apache config: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> <VirtualHost *:8000> <Location /> #the / has to be there, otherwise Apache startup fails Deny from all AuthUserFile /usr/local/etc/httpd/users AuthName authorization AuthType Basic Satisfy Any require valid-user </Location> DocumentRoot /var/www/html/project ServerName teamproject.example </VirtualHost> -
Websocket disconnecting again and again in django
I am trying to build a one on one chat application using django channels and websockets.I am following this tutorial https://youtu.be/RVH05S1qab8.I am getting this error when I try http://127.0.0.1:8000/raunak2/ in the url : [Failure instance: Traceback: <class 'ValueError'>: No route found for path 'raunak2/'. C:\Users\lenovo\Envs\lend\lib\site-packages\autobahn\websocket\protocol.py:2841:processHandshake C:\Users\lenovo\Envs\lend\lib\site-packages\txaio\tx.py:366:as_future C:\Users\lenovo\Envs\lend\lib\site-packages\twisted\internet\defer.py:191:maybeDeferred C:\Users\lenovo\Envs\lend\lib\site-packages\daphne\ws_protocol.py:72:onConnect --- <exception caught here> --- C:\Users\lenovo\Envs\lend\lib\site-packages\twisted\internet\defer.py:191:maybeDeferred C:\Users\lenovo\Envs\lend\lib\site-packages\daphne\server.py:200:create_application C:\Users\lenovo\Envs\lend\lib\site-packages\channels\staticfiles.py:41:__call__ C:\Users\lenovo\Envs\lend\lib\site-packages\channels\routing.py:54:__call__ C:\Users\lenovo\Envs\lend\lib\site-packages\channels\security\websocket.py:37:__call__ C:\Users\lenovo\Envs\lend\lib\site-packages\channels\sessions.py:47:__call__ C:\Users\lenovo\Envs\lend\lib\site-packages\channels\sessions.py:145:__call__ C:\Users\lenovo\Envs\lend\lib\site-packages\channels\sessions.py:169:__init__ C:\Users\lenovo\Envs\lend\lib\site-packages\channels\middleware.py:31:__call__ C:\Users\lenovo\Envs\lend\lib\site-packages\channels\routing.py:150:__call__ ] WebSocket DISCONNECT /raunak2/ [127.0.0.1:65338] I didn't get a perfect solution for this problem but I have solutions like removing '$' from the URL from routing.py but this is not working. My routing.py: application= ProtocolTypeRouter({ 'websocket':AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter([ re_path(r"^messages/(?P<username>[\w.@+-]+)", ChatConsumer), ] ) ) ) }) My app urls.py: urlpatterns=[ path("inbox",InboxView.as_view()), re_path(r"^(?P<username>[\w.@+-]+)/", ThreadView.as_view()), ] JS code: <script src="https://cdnjs.cloudflare.com/ajax/libs/reconnecting-websocket/1.0.0/reconnecting-websocket.min.js" integrity="sha512-B4skI5FiLurS86aioJx9VfozI1wjqrn6aTdJH+YQUmCZum/ZibPBTX55k5d9XM6EsKePDInkLVrN7vPmJxc1qA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script> var loc=window.location var formData=$("#form") var msgInput=$("#id_message") var chatHolder=$("#chat-items") var me=$("#myUsername").val() var wsStart='ws://' if(loc.protocol=='https:'){ wsStart='wss://' } var endpoint =wsStart + loc.host + loc.pathname var socket= new ReconnectingWebSocket(endpoint) socket.onmessage=function(e){ console.log("message",e) var chatDataMsg=JSON.parse(e.data) chatHolder.append("<li>"+ chatDataMsg.message +"via"+ chatDataMsg.username +"</li>") } socket.onopen=function(e){ console.log("open",e) formData.submit(function(event){ event.preventDefault() var msgText=msgInput.val() // chatHolder.append("<li>"+ msgText + " via "+me + "</li>") // var formDataSerialized=formData.serialize() var finalData={ 'message': msgText } socket.send(JSON.stringify(finalData)) // msgInput.val('') formData[0].reset() }) } socket.onerror=function(e){ console.log("error",e) } socket.onclose=function(e){ console.log("close",e) } </script> pip freeze: aioredis==1.3.1 asgi-redis==1.4.3 … -
How to update user password and store inside the database using django
I am trying to allow the admin to update the staff password, email address and username but the new password, email address and username is not updated into my database, did I do anything wrong in the code? The images below is how the main page looks like: This images show the next page which is the page that the staff password, username and email address will be updated: views.py def update(request, id): context = {} user = get_object_or_404(User, id=id) if request.method == "POST": user.save() return redirect("/allstaff") return render(request, 'allstaff.html', context) urls.py from django.urls import path from . import views urlpatterns = [ #path('', views.index, name='index'), #path('login/', views.login_view, name='login_view'), path('register/', views.register, name='register'), path('adminpage/', views.admin, name='adminpage'), path('customer/', views.customer, name='customer'), path('logistic/', views.logistic, name='logistic'), path('forget/', views.forget, name='forget'), path('newblock/', views.newblock, name='newblock'), path('quote/', views.quote, name='quote'), path('profile/', views.profile, name='profile'), path('adminprofile/', views.adminprofile, name='adminprofile'), path('', views.login_user, name='login'), path('home/', views.home, name='home'), path('allstaff/', views.allstaff, name='allstaff'), path('delete/<int:id>/', views.delete, name='delete'), path('update/<int:id>/', views.update, name='update'), path('logout/', views.logout_view, name='logout'), path('register/', views.register_view, name='register'), path('edit-register/', views.edit_register_view, name='edit_register'), ] updatestaff.html <!doctype html> {% extends "home.html" %} {% block content %} {% load static %} <html lang="en"> <head> <style> .button { background-color: #38d39f; border-color: #38d39f; color: white; padding: 10px 20px; text-align: center; display: inline-block; margin: 4px 2px; cursor: pointer; … -
Update key value in JSONField()
I'm trying to bulk update lots of records (3.2 million). This is my model: class MyModel(models.Model): stats = JSONField() Where stats is typically saved as: { "my_old_key": [{"hey": "Hello World"}] } I want to update it so that only the key changes it's value and final stats look like this (though there are records with "my_new_key" already so preferably skip those somehow): { "my_new_key": [{"hey": "Hello World"}] } I can do it in Python but it works really slowly.. I've tried on ~10k records with batching approach from this link so that the queryset is not fetched entirely into the memory. Final solution looked like this: def update_queryset(queryset) -> None: for stat in queryset: dictionary = stat.stats if "my_old_key" in dictionary: dictionary["my_new_key"] = dictionary.pop("my_old_key") stat.save() It does work but unfortunately it works too slowly :(. I thought about not fetching it to python at all and working purely on database somewhat like this answer suggested but didn't manage to make it work. Any suggestions on how I can speed it up / write RawSQL / make the jsonb_set approach work? -
You are trying to add a non-nullable field 'agent' to lead without a default; we can't do that (the database needs something to populate existing row
i'm making crm when i type python manage.py makemigrations i got this error: You are trying to add a non-nullable field 'agent' to lead 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) Quit, and let me add a default in models.py Select an option: Here's my models.py: from django.db import models from django.contrib.auth.models import User, AbstractUser class User(AbstractUser): pass class Lead(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) phone = models.BooleanField(default=False) agent = models.ForeignKey("Agent",on_delete=models.CASCADE) class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Here's my settings.py: """ Django settings for crm project. Generated by 'django-admin startproject' using Django 3.1.4. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '#zi%h*+ya0z(xi6j&^3uxvv$ak3=lj5wl5&q$zh3pwv9gwk03x' # SECURITY WARNING: don't run with debug turned on in production! DEBUG … -
how i get primary key in string format in django rest framework
i'm currently working on django rest framework project and the requirement of output of the response is described below. if any one have an idea about this, it will be very helpful for me. currently i'm getting output like this: { "status": true, "message": "User Details", "Detail": { "id": 1, "phone": "9874563120", "first_name": "Crish", "birthdate": "1989-09-16", "age": 32, "email": "crish@gmail.com", } } But i want to get output like this: { "status": true, "message": "User Details", "Detail": { "id": "1", #in string formate "phone": "9874563120", "first_name": "Crish", "birthdate": "1989-09-16", "age": "32", #in string formate "email": "crish@gmail.com", } } what change should i make to gat this type of output! -
Contrib-auth-validate give None even when input is correct
Here is my Code: class LoginSerializer(serializers.Serializer): isd = serializers.IntegerField(write_only=True, required=False) email = serializers.CharField(required=False, source='username') phone = serializers.CharField(required=False) username = serializers.CharField(required=False) password = PasswordField(required=True) def create(self, validated_data: dict): if not validated_data.__contains__('username'): print("validated_data",validated_data) validated_data['username'] = validated_data['phone'] print("validated_data",validated_data) user: AppUser = authenticate(**validated_data) print("user",user) if not user or not user.is_active: raise AuthenticationFailed('Username or password is incorrect.') print("user",user) return user and Here is output: validated_data {'isd': 91, 'phone': '123', 'password': '123'} validated_data {'isd': 91, 'phone': '123', 'password': '123', 'username': '123'} user None Forbidden: /auth/user/login/ Even though im using same username and password From django admin user: AppUser = authenticate(**validated_data) print("user",user) is giving me None Value -
django order by aggregate value from non-related table
I have two models, Accrual and Member, and the common field of these two models is register_no, but this field is not a foreign key class Accrual(models.Model): register_no = models.PositiveIntegerField(verbose_name=_('Register No')) amount=models.DecimalField(decimal_places=2, max_digits=17, verbose_name=_('Total Amount')) class Member(models.Model): register_no = models.PositiveIntegerField(unique=True, verbose_name=_('Register No')) I want to list the debt each member has. It can be done with @property; class Member(models.Model): register_no = models.PositiveIntegerField(unique=True, verbose_name=_('Register No')) @property def debt(self): ret_val = Accrual.objects.filter(register_no=self.register_no).aggregate( debt=Sum('amount')) debt = ret_val.get('debt', 0) return debt if debt else 0 but I can't use order_by this way. I want to sort each member by debt. How can I solve this problem? -
Reading HTML form name in Django views
I want to define a view that should display from which page the request is coming. for example: 'Request is coming from index page' 'Request is coming from home page' ................... ................ so on views.py def practice(request): return HttpResponse(request.POST) it is displaying all the form fields but I am not able to get the form name. Html: {% extends 'base.html' %} <html> <head> <meta charset="UTF-8"> </head> <body> {% block content %} <h1>Creating Incident</h1> <form name = "index" action = 'practice' method = "post"> {% csrf_token %} <center> <table> <tr><td>Support portal username</td><td>:</td><td><input type = 'text' name = USERNAME size="50"></td></tr> <tr><td>Your Email</td><td>:</td><td><input type = 'text' name = EMAIL size="50"></td></tr> <tr><td>Password</td><td>:</td><td><input type = 'password' name = PASSWORD size="50"></td></tr> <tr><td>Xtreme ID</td><td>:</td><td><input type = 'text' name = COMPANYID size="50"></td></tr> <tr><td>Customer email </td><td>:</td><td><input type = 'text' name = CUSTOMEREMAIL size="50"></td></tr> <tr><td>Event Note </td><td>:</td><td><textarea id="eventnote" name= EVENTNOTE rows="8" cols="48"></textarea></td></tr> </table><br> <input type = 'submit' value = 'submit'> <a href="Home"><input type="button" value="Home"></a> </center> </form> {% endblock %} </body> </html> -
assigning role for different users in Django Rest Framework
I have used AbstractUser defined in Django for user model and have a UserProfile model which is one to one relation with the User. Now I have to implement a role-based authorization for the CRM project that I am writing. What will be the best approach to assign a role? Should I use add fields inside the user model or inside the UserProfile model? Or I should use the already defined superuser,is_staff or active status inside User model. My models: class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self,first_name,last_name,email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError("The email must be set") first_name = first_name.capitalize() last_name = last_name.capitalize() email = self.normalize_email(email) user = self.model( first_name=first_name, last_name=last_name, email=email, **extra_fields ) #user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self.db) return user def create_superuser(self, first_name,last_name,email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(first_name,last_name,email, password, **extra_fields) class CustomUser(AbstractUser): … -
DRF nested router serializer source fields from url
I have an author and books model. An author has many books with him class Author(Model): id = UUIDField(primary_key=True, default=uuid4, editable=False) name = CharField(max_length=50) email = CharField(max_length=50) class Book(Model): id = UUIDField(primary_key=True, default=uuid4, editable=False) name = CharField(max_length=50) author = ForeignKey(Author, on_delete=models.CASCADE) In my urls.py author_router = SimpleRouter() author_router.register( r"author", AuthorViewSet, basename=author" ) nested_author_router = NestedSimpleRouter(author_router, r"author", lookup="author") nested_author_router.register(r"book", BookViewSet) In my searlizers.py class BookSerializer(ModelSerializer): class Meta: model = Book fields = ( "id", "name", "author", ) extra_kwargs = { "id": {"required": False}, "author": {"required": False}, } class AuthorSerialzer(ModelSerializer): class Meta: model = Author fields = ( "id", "name", "email", ) extra_kwargs = { "id": {"required": False}, } In views.py class BookViewSet(GenericViewSet): queryset = Book.objects.all() serializer_class = BookSerializer def create(self, request, author_pk): data = request.data data["author"] = author_pk serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) Since books are related to the author and I am using nested routers the curl call would look like curl --location --request POST 'localhost:8000/author/1/book' --data '{"name": "Book Name"}' In my BookViewSet I end up manually adding the author_pk to the data object before calling serializer is_valid method. Is there a way to specify the source from URL route or any better way of doing this? -
Heroku: "No default language could be detected for this app" error thrown for node app
Heroku: "No default language could be detected for this app" error thrown for node app ... enter image description here -
how can i call all the emails in or i want to add more fields to it it this is my git repo https://github.com/rahullabroo0/django-react-auth-main.git
i am trying to know how can i call all the emails in it? or i want to add more fields to it it this is my git repo https://github.com/rahullabroo0/django-react-auth-main.git and is there any standard method to use login registration code. plz send me the links and also tell me to how to work on multiple table in django. in dashboard i want to show all the emails from table. this is the code -
Is it possible to determine routes to a location along with its distance using GeoDjango?
We have a food delivery project and we use GeoDjango for storing the locations of vendors and for determining the nearby vendors by calculating the distance of customers and vendors. Now, we want to filter the nearby vendors based on the distance of routes. Like for example, get the vendors that have 10km distance based on routes to the location of customer. Is it possible in GeoDjango? Can you recommend libraries that have that functionality? -
How to manipulate/compress uploaded image and save it to AWS S3 using boto3
I want to manipulate/compress the uploaded image and then save it on the S3 bucket. Here is what I have tried so far: S3 = boto3.client("s3", aws_access_key_id=settings.ACCESS_KEY_ID,aws_secret_access_key=settings.SECRET_ACCESS_KEY) image = Image.open(img) outputIoStream = BytesIO() temp_image = image.resize((1020, 573)) temp_image.save(outputIoStream, format='PNG', quality=60) outputIoStream.seek(0) img = InMemoryUploadedFile(outputIoStream, 'ImageField', " {}.png".format(img.name.split('.')[0]), 'text/plain', sys.getsizeof(image), None) key = f"post/" + str(request.user.id) + "/" + str(img) S3.put_object(Bucket="zappa- legends", Body=img, Key=key) I am getting the following error: An error occurred (BadDigest) when calling the PutObject operation (reached max retries: 4): The Content-MD5 you specified did not match what we received. What should I do to avoid such errors? -
Is there a way to subscribe and send personal messages to slack users in a workspace with python
I have a to create a webapp that sends messages to specific users asking them if they want to see a daily report of their progress. I have to develop this in django and celery. This is the requirement that got me in trouble: The employees should not be able to see other's reports. The slack reminders must contain an URL to today's report with the following pattern https://domain_of_my_app/report/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (an UUID), this page must not require authentication of any kind. I think that link must be unique to the users but I have no idea how to deal with this in slack Any ideas? -
How to get data from url in django?
I want to send contid and cid to the function through the url . I included the path in the urls.py path('contracts/ctinfo/<int:contid>/<int:cid>',contract.ctinfo), # when contid and cid both present path('contracts/ctinfo/<int:cid>',contract.ctinfo), # when only cid is present contract.py def ctinfo(request,cid=None,contid=None): print(cid,contid) return render(some.html) When I am accessing http://localhost:8000/contracts/ctinfo/15000/99 I am getting cid=99 but contid=0 Why I am getting 0? Is there any other way to do this? -
Django - Django not returning all entities from table on GET call
I have this get function def get(self, request): items = Post.objects.order_by('created').annotate( creator_name=F('creator_id__username'), goal_description=F('goal_id__description'), replies=Count('replypost', distinct=True), cheers=Count('cheerpost', distinct=True), ).prefetch_related( Prefetch('photo_set', Photo.objects.order_by('created')) ) serializer = FullPostDataSerializer(items, many=True) return Response(serializer.data, status=status.HTTP_200_OK) It should ideally be returning all the posts ordered by time, but for some reason when I debug and return serializer.data all I get on the front-end is: But when I use PGAdmin to look at the table You can clearly see there are more recent posts than september 13th. What's going on?