Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: annotate a model with multiple counts is super slow
I'm trying to annotate a model that has multiple relationships, with multiple counts of those relationships. But the query is super slow. Campaign.objects.annotate( num_characters=Count("character", distinct=True), num_factions=Count("faction", distinct=True), num_locations=Count("location", distinct=True), num_quests=Count("quest", distinct=True), num_loot=Count("loot", distinct=True), num_entries=Count("entry", distinct=True), ) When I mean super slow, I mean it: it takes multiple minutes on my local MacBook Pro with the M1 Max 😰 And there aren't even that many row in these tables. If I simply fetch all campaigns, loop over them, and then get the counts of all these related objects in separate queries, it's a LOT faster (at the cost of doing number of campaigns * 6 queries). But that is so much more code to write, can't this query be optimized somehow? -
Django: How to get list of choices of choice field
I have Choices: all_choices= Choices( ('val1', _("val1 text")), ('val1', _("val2 text")), ('val3', _("val3 text")), ('val4', _("val4 text")), ) I am looking for function that returns list of all choices like: list=['val1', 'val2', 'val3', 'val4'] I could not manage to do it so far Is there any proper wat to get list of choices? -
self.request.user not returning in queryset
In my views, queryset is returning all the users when I want it to be only returning the user that is currently logged. I have a get self method which has the serializer set to the user but it is not being used. When I tried get_queryset, self.request.user still doesn't return the user. views.py: from rest_framework import viewsets from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from rest_framework import status from rsm_app.api.v1 import serializer as serializers from rsm_app.users.models import User class CurrentUserView(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) serializer_class = serializers.UserSerializer #queryset = User.objects.filter(name=request.user.name) def get_queryset(self): return self.request.user def put(self, request): serializer = serializers.UserSerializer( request.user, data=request.data) if request.data and serializer.is_valid(): serializer.save() return Response(serializer.data) return Response({}, status=status.HTTP_400_BAD_REQUEST) Url.py: from rest_framework import routers from django.urls import path, re_path, include from graphene_django.views import GraphQLView from rsm_app.api.v1 import views app_name = "api.v1" # Routers provide an easy way of automatically determining the URL conf. router = routers.DefaultRouter() router.register(r"user", views.CurrentUserView, basename="user") # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path("graphql", GraphQLView.as_view(graphiql=True)), re_path(r"^", include(router.urls)), re_path(r"user/", views.CurrentUserView, name='user'), re_path(r"^api-auth/", include("rest_framework.urls", namespace="rest_framework")), ] -
Get slug name list by url path name
I am reverse-engineering django urlpatterns. For my purpose, I need to dynamically know the list of slug names developers chose to use within url. Example: path("<slug:membership_slug>/<slug:parent_slug>/data/", rzd.ReportingUnitDataView.as_view(), name="hierarchy.item.data"), So, in the world, where everyone writes perfect code, my function should take "hierarcy.item.data" and spit out ["membership_slug", "parent_slug"] I looked at the reverse function, hoping it would return something useful without kwargs, but it does not. Have been googling like Neo, but to no avail. But the hope does not leave my heart... somewhere django should hold all that urlpatterns stuff! I still believe. Perhaps you can at suggest how to get a hold of list of urls, even if in the raw format, that would already be a help. Thank you. -
how to fix result display in project
How to adjust the project to improve the performance result: in myworld/members/view.py: def testing(request): template = loader.get_template('template.html') context = { 'heading': 'Hello &lt;i&gt;my&lt;/i&gt; World!', } print(context) return HttpResponse(template.render(context, request)) in myworld/members/templates/template.html : <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Learning_21_1_1</title> </head> <body> {% autoescape off %} <h1>{{ heading }}</h1> {% endautoescape %} <p>Check out views.py to see what the heading variable looks like.</p> </body> </html> result : enter image description here main result : enter image description here enter image description here please help me -
Django summernote don't form is not displayed outside the admin panel
I'm trying to add WYSIWYG editor django-summernote to my django project. I found the problem that the editor is not showing up when I try to add it to the page. On the form page, I don't have the summernote editor displayed. There is an error in the console with jQuery. Error: jquery-3.6.0.min.js:2 jQuery.Deferred exception: Cannot read properties of null (reading 'value') TypeError: Cannot read properties of null (reading 'value') at HTMLDocument.<anonymous> (http://127.0.0.1:8000/summernote/editor/id_description/:43:25) at e (http://code.jquery.com/jquery-3.6.0.min.js:2:30038) at t (http://code.jquery.com/jquery-3.6.0.min.js:2:30340) undefined S.Deferred.exceptionHook @ jquery-3.6.0.min.js:2 t @ jquery-3.6.0.min.js:2 Объект setTimeout (асинхронный) (анонимная) @ jquery-3.6.0.min.js:2 c @ jquery-3.6.0.min.js:2 fireWith @ jquery-3.6.0.min.js:2 fire @ jquery-3.6.0.min.js:2 c @ jquery-3.6.0.min.js:2 fireWith @ jquery-3.6.0.min.js:2 ready @ jquery-3.6.0.min.js:2 B @ jquery-3.6.0.min.js:2 jquery-3.6.0.min.js:2 Uncaught TypeError: Cannot read properties of null (reading 'value') at HTMLDocument.<anonymous> ((индекс):43:25) at e (jquery-3.6.0.min.js:2:30038) at t (jquery-3.6.0.min.js:2:30340) Screen enter image description here Code: # Settings.py INSTALLED_APPS = [ ... 'django_summernote', # WYSIWYG EDITOR 'editorapp', # my app ... ] MEDIA_URL = 'media/' MEDIA_ROOT = BASE_DIR / 'media' # Urls urlpatterns = [ ... path('editorapp/', include('editorapp.urls')), path('summernote/', include('django_summernote.urls')), ... ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # models.py class NodesForm(forms.ModelForm): description = SummernoteTextField() class Meta: model = Nodes fields = ('node_description',) # urls.py path('', views.main, name='nodedoc_main'), … -
JS function not fired in Django dropdown onchange event
I've question, I've JS function which is used in Django project(downloaded from internet) , so in template.html I've <select class="select_filter" onchange="myFunc(this.value);"></select>, also this function is declareted in this template.html <script> function myFunc(val) { console.log(val); } </script> but in DevConsole in browser I got Uncaught ReferenceError: myFuncis not defined P.S Jquery was enabled in page-source (checked from Ctrl+U) Can anyone please guide and help with my problem? -
update only targeted element with ajax
I'm trying to update my cart page with ajax when someone increases or decreases the quantity of the products, my view logic is fine. My issue as I can infer is targeting the class "ajax_updater", as soon as I hit the quantity buttons ajax works, but instead on just the specific product, it targets all the products' quantity with the same class ".quantity-style" and changes the value as per the targeted product, so, if the quantity for product A is 4 after ClickEvent, the quantity for product B, D, F gets targeted and changed to 4 too, what could be a solution? {% for item in items %} <div class="quantity"> <p id="quantity-style" class="quantity-style">{{item.quantity}}</p> <div class="quantity-arrows"> <img data-product="{{item.product.id}}" class="ajax_updater" data-action="add" src="{% static 'shop/images/arrow-up.png' %}"> <img data-product="{{item.product.id}}" class="ajax_updater" data-action="remove" src="{% static 'shop/images/arrow-down.png' %}"> </div> </div> {% endfor %} function update_arrow() { $.ajaxSetup ({ cache: false }); var spinner = '<i class="fas fa-circle-notch fa-spin" style="font-size:15px;" alt="loading" ></i>'; $(".quantity-style").html(spinner).load(update_quantity_url); console.log(update_arrow_url); } $('.ajax_updater').click(function () { update_arrow(); console.log('hit hit'); }); -
What is the difference between SimpleTestCase.settings() and django.test.override_settings?
Django provides different ways to change settings(documentations) in a test in different levels (TestCase class, test method, context manager). I understand the difference between override_settings and modify_settings, but I can't get the difference between SimpleTestCase.settings() and django.test.override_settings() when being used as a context manager. Is there any difference in functionality or preference in which one to use? -
(Django / Nginx / Gunicorn) HTTPS fails to serve pathed directories on my site
Pretty new to Nginx and web deployment in general. I have a site I am aiming to deploy using a DigitalOcean droplet. Right now it is working, but only with http://[SERVER-IP] (here) Although the site does load with HTTPS (here), no domain.com/[ X ] sites work. The aim is to make get all URLs within https://rejesto.com functioning normally and leading to their respective sites. For context, all links on the page are provided by Djagno's {% url '[url]' %} tag system; they work as intended locally, and using http://[SERVER-IP]/[ X ]. I'm assuming that the issue is within the Nginx config files because: http://46.101.92.95/blog leads to the correct page. (for better or for worse) https://rejesto.com/blog does not work. Here is (what I believe to be) the relevant config file: /etc/nginx/sites-available/rejesto.com: server { server_name rejesto.com www.rejesto.com; location / { try_files $uri $uri/ =404; include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/rejesto/myprojectdir; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/rejesto.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/rejesto.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by … -
UpdateAPIView | Django REST does not update data properly
I want to register values in a table of relations when updating data. Conversely, I want to generate an error if the value does not exist. models.py class CustomUser(AbstractBaseUser, PermissionsMixin): uuid = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) email = models.EmailField(_('email address'), unique=True) role = models.OneToOneField('Role', related_name='user', blank=True, null=True, on_delete=models.PROTECT) # ommited... class Role(models.Model): slug = models.SlugField(unique=True) def __str__(self): return self.slug serializers.py from drf_writable_nested import WritableNestedModelSerializer from rest_framework import serializers from accounts.models import CustomUser, Role class RoleSerializer(serializers.ModelSerializer): class Meta: model = Role fields = ('slug',) class UserSerializer(WritableNestedModelSerializer): role = RoleSerializer() class Meta: model = CustomUser fields = ('uuid', 'email', 'role', 'password') extra_kwargs = {'password': {'write_only': True, 'required': True}} def create(self, validated_data): return CustomUser.objects.create_user(**validated_data) views.py class UserUpdateView(generics.UpdateAPIView): queryset = CustomUser.objects.all() serializer_class = UserSerializer Role DB Table id:1 | slug:admin Expectation Request(PATCH) Parameter { "role":{ "slug":"foo" } } # error: foo does not exist in the Role table { "role":{ "slug":"admin" } } # OK!!! What should I do? Thank you very much. -
How to obtain a specific data from model in profile when person is logged in, Django?
I want to post a specific data in profile from user that is logged in. I have a model like this: class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=60) email = models.EmailField(max_length=100) class Wallet(models.Model): name = models.OneToOneField(User, null=True, on_delete=models.CASCADE) usd = models.FloatField(null=True) If for example 'user2' is logged in, and in database he has 10usd, I want in his profile to be shown 10usd. But I don't know how to request a specific data of user that is logged in Views.py @login_required(login_url='main') def profile_user(request): usd = wallet.objects.get (get his usd from db) return render(request, 'profile.html', {'usd':usd}) Thank you very much. -
Issue deploying Django webapp in OVH Hosting
I'm trying to deploy a Django App in OVH Hosting and, after some hard exploration and try-error, I keep getting an issue. File "/usr/share/passenger/helper-scripts/wsgi-loader.py", line 381, in <module> handler = RequestHandler(server_socket, sys.stdin, app_module.application) AttributeError: module 'passenger_wsgi' has no attribute 'application' OVH/Passenger proccess feedback Apart from all the files created at startapp by Django and all the code I wrote I added the following file 'passenger_wsgi.py' on the root of the app directory. I used two differents versions: First: import MyApp.wsgi application = MyApp.wsgi.application Second: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() In the runtime configuration of OVH hosting the application launch script set is 'manage.py'. SECRET_KEY and DJANGO_SETTINGS_MODULE are declared in the environment variables. -
How can I find 3 top or max value in django model?
I have a class in django model and how can I find 3 maximum value in it? Do I need for into for loop? or Do I need any class? class Prices (models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) Price = models.IntegerField() page = models.ManyToManyField(Listing_page,blank=True,related_name='Price') def __str__(self) -> str: return f"{self.id} : {self.Price}" I have follow code for top price but I need 3 top price too. big_price = None for num in post.Price.all(): if (big_price is None or num.Price > big_price.Price): big_price = num -
Using the URLconf defined in name, Django tried these URL patterns, in this order
I have a django project and in this project I have two apps: main and profiles. So I added both mini apps to the settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'profiles', ] and I can run the main application - if I go to: http://127.0.0.1:8000/ It is running. But If I go to: http://127.0.0.1:8000/profiles Then I get this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/profiles Using the URLconf defined in schoolfruitnvwa.urls, Django tried these URL patterns, in this order: admin/ [name='index'] The current path, profiles, didn’t match any of these. So my question is: how to tackle this? Thank you -
How to mark words that match words from a list in a django form's textarea using javascript?
I have the following form: class TestForm(Form): testfield = CharField(widget=Textarea(attrs={'rows': 10, 'id': 'test'}), label='Input test text here') Rendered to my template along with the following list as context: dummy_list = ['hi', 'hello'] I'm trying to make a button which I can click in my template which makes words in the form bold if they are contained within the list. JS: <script type="text/javascript"> function Mark_words(id) { var form_content = document.getElementById(id); var dummylist = {{ dummy_list }} var new_form_content = "" for(var x in form_content.value) { if ( dummylist.indexOf(x) > -1 ){ x = x.bold(); new_form_content += x + " "; } else { new_form_content += x + " "; } } form_content.innerText = new_form_content; } </script> And the following button: <button type = "submit" class ="btn btn-info" value = "Click" onclick="Mark_words('test')">Mark words</button> Unfortunately, nothing happens when I click the button. What am I doing wrong? -
Django: relations between two objects of the same model
I have created this model: class Process(models.Model): name = models.CharField('Process name', max_length=50, unique=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, max_length=50, null=True, verbose_name='Process owner') I want to create multiple processes and from those build a hierarchy. Here is a hierarchy model: class Hierarchy(models.Model): name = models.ForeignKey('process.Process', on_delete=models.CASCADE, verbose_name='Sub process name') name = models.ForeignKey('process.Process', on_delete=models.CASCADE, verbose_name='Main process name') order = models.IntegerField('Process order', default='1') Obviously this doesn't work as the 'name' fields in hierarchy model interfere with each other. I wouldn't want to create models MainProcess and SubProcess as some SubProcesses might have more SubProcesses etc. What would be the right way to build this type of model/hierarchy? This might be very basic issue, but I couldn't find any related issues to apply a solution from, so any help would be appreciated. -
XXX is not defined - Importing Class from OpenLayers Node Module in Django
Having difficulty getting the Node OpenLayers to work within Django. npm and ol are installed and the files are in a node_modules folder in my project. I included the node_modules folder in my STATICFILES_DIRS in settings.py. I'm including the OpenLayers modules within my template, map.html: <script type="module" src="{% static 'ol/dist/ol.js' %}"></script> <script type="module" src="{% static 'ol/Map.js' %}"></script> <script type="module" src="{% static 'ol/View.js' %}"></script> <script type="module" src="{% static 'ol/layer/Tile.js' %}"></script> <script type="module" src="{% static 'ol/source/OSM.js' %}"></script> <script type="text/javascript"> import "{% static 'ol/layer/Tile.js' %}"; const map = new ol.Map({ target: 'my-map', layers: [ new ol.Layer.Tile({ source: ol.Source.OSM() }) ], view: new ol.View({ center: [40, -70], zoom: 2 }) }); </script> Which appears to be working as I can see the files load within my browser's dev tools. But when I try to use the classes within the modules I get the error: Uncaught ReferenceError: ol is not defined OTHER METHODS I'VE TRIED: I've also tried calling the class names directly: <script type="text/javascript"> const map = new Map({ target: 'my-map', layers: [ new Tile({ source: OSM() }) ], view: new View({ center: [40, -70], zoom: 2 }) }); </script> But get the same error: Uncaught ReferenceError: Tile is not defined The OpenLayers docs … -
Wagtail dumpdata modellogentry null values
Having a problem with dumpdata command in Wagtail v.3.0.3. Some of the entries for the table pagelogentry have data set to null and not the expected {}. It is not all the values. When I do dumpdata I have to edit the dump file by hand to allow it to work with loaddata. e.g. { "model": "wagtailcore.pagelogentry", "pk": 2, "fields": { "content_type": [ "home", "gallerypage" ], "label": "Excellence in Engineering", "action": "wagtail.publish", "data": null, "timestamp": "2020-08-18T16:25:08.456Z", "uuid": null, "user": [ "egomez" ], "content_changed": true, "deleted": false, "page": 2702, "revision": 7602 } } We have had this site for a few years and it has been updated through various Wagtail versions. I'm not sure what the right course to fix the data is here. -
django How do I get a value from a model recursive reference?
I am trying to implement the comment function of comments through self reference. error: models.ReComment.DoesNotExist: ReComment matching query does not exist. Parent_comment of ReComment model was ForeignKey as self I printed self.kwarg and got a value of {'pk': 3, 'comment_id': 8} models.py class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() feeling = models.CharField(max_length=50, validators=[validate_no_numbers, validate_no_special_characters]) score = models.IntegerField(validators=[validate_score, validate_no_special_characters]) dt_created = models.DateTimeField(auto_now_add=True) dt_update = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") likes = GenericRelation("Like", related_query_name="post") def __str__(self): return self.title class Comment(models.Model): content = models.TextField(max_length=500, blank=False) dt_created = models.DateTimeField(auto_now_add=True) dt_update = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="comments") post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") likes = GenericRelation("Like", related_query_name="comment") def __str__(self): return self.content[:30] class ReComment(models.Model): comment = models.ForeignKey(Comment, on_delete=models.CASCADE, related_name="recomments") content = models.TextField(max_length=500, blank=False) dt_created = models.DateTimeField(auto_now_add=True) dt_update = models.DateTimeField(auto_now=True) parent_comment = models.ForeignKey("self", blank=True, null=True, on_delete=models.CASCADE, related_name="parent_comments") def __str__(self): return self.content[:30] form.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = [ "content", ] widget = { 'content': forms.Textarea, } class ReCommentForm(forms.ModelForm): class Meta: model = ReComment fields = [ "content", ] views.py class CommentCreateView(LoginAndVerificationRequiredMixin, CreateView): http_method_names = ["post"] model = Comment form_class = CommentForm def form_valid(self, form): form.instance.author = self.request.user form.instance.post = Post.objects.get(id=self.kwargs.get("pk")) return super().form_valid(form) def get_success_url(self): return reverse("post-detail", kwargs={"pk":self.kwargs.get("pk")}) class ReCommentCreateView(LoginAndVerificationRequiredMixin, CreateView): http_method_names … -
Wagtail PageRevision errors from loaddata
When I use dumpdata / loaddata to snapshot my live Wagtail sites to my sandbox, I sometimes get pages which I can't edit on my sandbox. These are always pages which the Wagtail admin explorer has marked "live + draft". They produce a 500 error, can't currently handle on_delete types other than CASCADE, SET_NULL and DO_NOTHING but the stack trace shows the cause is a ContentType matching query does not exist. The only way to make them editable on the sandbox is to remove the PageRevision for each of the pages locally, via Django/python shell. Is there an approved way to fix these pages to remove the spurious drafts? -
Error converting data type nvarchar to Datetime While Calling Store Procedure in Django
I am trying to pass datetime value to the store procedure of mssql but getting this error: django.db.utils.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Error converting data type nvarchar to datetime. (8114) (SQLExecDirectW)') Here is the code: fromDate = datetime(2022, 1, 1) toDate = datetime(2022, 12, 31) dealershipId = request.GET['dealershipId'] cursor = connection.cursor() cursor.execute(f"EXEC proc_LoadJobCardbyDateRange [@Fromdate={fromDate}, @Todate={toDate}, @DealershipId={dealershipId}]") result = cursor.fetchall() I have tried to pass datetime object in order to execute store procedure. I also tried to pass datetime as string but the same error persists. I also tried different formats but it didn't work as mentioned in some solutions that I have searched for. Please guide me as to why I am having this issue and what's the correct solution to this can be? -
Django password hashing different from python passlib pbkdf2 library
Using django admin, I have created a user email: cuteemail@example.com password: ccpass!ccpass The hashed password stored in the database is pbkdf2_sha256$260000$alGB1h2BRHwn83nz9fSJ3V$qippfbL8g59KPoDh+cIEh70TQCjuWeH8017VcLLpDIY= All I know is that django is generating the password hash using PBKDF2 algorithm. I need to run a pure python script that inside a part of it, it checks if a password is matching a hash. I have found a library passlib. I can provide the password and rounds. But where does the django salt come from? from passlib.hash import pbkdf2_sha256 password = 'ccpass!ccpass' db_hashed_password = 'pbkdf2_sha256$260000$alGB1h2BRHwn83nz9fSJ3V$qippfbL8g59KPoDh+cIEh70TQCjuWeH8017VcLLpDIY=' salt = db_hashed_password.split('$')[2].encode() pbkdf2_sha256.hash(password, rounds=260000, salt=salt) result: $pbkdf2-sha256$260000$YWxHQjFoMkJSSHduODNuejlmU0ozVg$qippfbL8g59KPoDh.cIEh70TQCjuWeH8017VcLLpDIY The resulted password hash apparently looks the same except minor differences. The pbkdf2-sha256 has a dash instead of an underscore but this is not a problem. I can fix it. The main problem is that I do receive a . instead of + in the actual hash part. How to fix this? Can I blindly replace all . with + ? -
Django Rest Framework - datetime sent as str gets changed to different timezone when being saved to database?
I sent the following: {'ticker': 'XYZ', 'last_price': 394.05, 'last_date_time': '2022-10-04 15:57:18'} When it was saved in DB: ticker: XYZ last_price: 394.05 last_date_time: 2022-10-04 11:57:18 I am not sure how or why this gets changed. models.py class StockPriceModel(models.Model): ticker = models.CharField(max_length=30, blank=False, db_index=True) last_price = models.FloatField(blank=True, null=True) last_date_time = models.DateTimeField(db_index=True) created_at = models.DateTimeField(auto_now_add=True) The auto_now_add field is also showing incorrect time. It doesn't correspond to my date time setup in settings as below: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Dubai' USE_I18N = True USE_L10N = True USE_TZ = True -
difference between Django ORM datetime and Postgre datetime value
I have developed an application with Django and recently changed my DB from Sqlite to Postgresql. I have found the following inconsistency between datetime values in DB and results of Django orm: and: You can see the difference between hours, mins and seconds. It should be noted that the column type is datetime and there is not any inconsistency if i use sqlite.