Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
validated data Django rest
I would like to validate data when I send post request, if data in db with the field country and value France exist, then raise ValidationError('Choose another country)' ,if not - create a new object in db. class MainSerializer(serializers.Serializer): email = serializers.EmailField() country = serializers.CharField(max_length=20) created = serializers.DateTimeField() class MainSerializer(serializers.Serializer): email = serializers.EmailField() country = serializers.CharField(max_length=20) created = serializers.DateTimeField() def create(self, validated_data): return Main(**validated_data) def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) instance.country = validated_data.get('content', instance.country) instance.created = validated_data.get('created', instance.created) return instance -
Is there a better solution to filter model objects by permission in django
I have a Django model Task containing permissions. from django.db import models from django.contrib.auth.models import Permission # Other stuff class TaskType(models.Model): required_permissions = models.ManyToManyField(Permission) # Other non relevant fields class Task(models.Model): begin = models.DateTimeField( #Options left out end = models.DateTimeField( #Options left out type = models.ForeignKey(TaskType, on_delete=models.CASCADE) # Other non relevant fields Now I have a view where a user is supposed to select a Task in a specific Time slot but should only choose from tasks where the user has the required permissions for and where the task in question wouldn't be blocked by another task in that time slot the user was already assigned to. My current solution to this problem is to query objects from the objects from the database that could be a valid candidates and filter out the ones the user has no permission for in python. This obviously feels a bit silly since this should be done by the database query (as database management systems are quite sophisticated for such tasks). My current solution looks like this: def is_task_valid(self, task): for p in task.type.permissions.all(): if not user.has_perm(p.content_type.app_label + "." + p.codename): return False: # Also checks for all assigned tasks of user in that … -
Why Password reset unsuccessful in django rest-auth password reset
I have problem with django rest-auth password rest. this is my urls.py file(main urls) from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi app_name= 'accounts' schema_view = get_schema_view( openapi.Info( title='Blog API', description='oddiy API loyixasi', default_version='v1', terms_of_service='``https://google.com.policies.terms``', contact=openapi.Contact(email="xatamjonovulugbek17@gmail.com"), license=openapi.License('Blog API litsenziasi'), ), public=True, permission_classes=(permissions.AllowAny, ), ) urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('accounts.urls')), path('', include('product.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('dj-rest-auth/', include('dj_rest_auth.urls')), path(r'^', include('django.contrib.auth.urls')), path('auth/', include('rest_framework.urls')), path('allauth/', include('allauth.urls')), path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-radoc'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I add path(r'^', include('django.contrib.auth.urls')), to urls.py. This url sent mail to counsol but I enter url in mail , I take this error: " Password reset unsuccessful The password reset link was invalid, possibly because it has already been used. Please request a new password reset. " Please give me solve I add path(r'^', include('django.contrib.auth.urls')), to urls.py. This url sent mail to counsol but I enter url in mail , I take this error: " Password reset unsuccessful The password reset link was invalid, possibly because it has already been used. Please request a new password reset. " Please give me … -
Django/Python - Get radiobutton value
I have a problem, I want to get the radiobutton value to my view, but I don't know how. What I have now is this: index.html <form class="card" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="radio" name="update_type" value={{view.choice1}}> Choice1 </input> <input type="radio" name="update_radio" value={{view.choice2}}> Choice2</input> <a href="{% url 'core:newview' slug=???? %}" class="btn btn-primary">Update</a> </div> </div> </div> </div> </form> views.py #index.html class view1(generic.TemplateView): extra_context = {"main_page": "active"} choice1 = 1 choice2 = 0 context_object_name = 'mainview' template_name = 'core/index.html' class NewView(generic.TemplateView): extra_context = {"mainx_page": "active"} context_object_name = 'newview' template_name = 'core/index.html' def get(self, request, queryset=None, *args, **kwargs): update_choice = self.kwargs.get('slug') print(update_choice) return redirect(reverse("core:mainview")) urls.py path('mailbox/mainview', login_required(views.MainView.as_view()), name='mainview'), path('mailbox/newview/<int:slug>/', login_required(views.NewView.as_view()), name='newview') Basically, I don't know what I should put at the place in the index.html where the ???? are now. I want to get a 0 as a value from self.kwargs.get('slug') when choice1 is selected in the radiobutton and a 1 when choice2 is selected. Another option is that I not get a 0 or 1 value, but rather returning it as a string: choice1 or choice2 Could someone help me, it's very much appreciated! -
In django-recurrence the between() method with inc=True includes dtstart even when there is no Recurrence then
This a question on jazzband's django-recurrence. I have model with a RecurrenceField: # models.py class Session(models.Model): # other fields dates = RecurrenceField(null=True) In the django admin, I add a rule: weekly, Mondays. I need to get all the Session dates of the current month (including those in the past). However, when I call between() with inc=True, and dtstart = the first day of the month (as decribed in the docs), then that dtstart is returned too (which is a Tuesday for March 2022): # shell output: In [7]: obj = Session.objects.all().first() In [8]: for rule in obj.dates.rrules: ...: print(rule.to_text()) ...: hebdomadaire, chaque lundi # translates to: weekly, every Monday In [9]: month_end Out[9]: datetime.datetime(2022, 3, 31, 0, 0) In [10]: month_start Out[10]: datetime.datetime(2022, 3, 1, 0, 0) In [11]: obj.dates.between(month_start,month_end,dtstart=month_start,inc=True,) Out[11]: [datetime.datetime(2022, 3, 1, 0, 0), # this is a Tuesday! datetime.datetime(2022, 3, 7, 0, 0), # Monday datetime.datetime(2022, 3, 14, 0, 0), # Monday datetime.datetime(2022, 3, 21, 0, 0), # Monday datetime.datetime(2022, 3, 28, 0, 0)] # Monday In [12]: obj.dates.between(month_start,month_end,dtstart=month_start,inc=True,)[0].weekday() Out[12]: 1 -
Django Model Form not saving data
I am working on Django application and I am trying to create form for users' suggestions and comments. I want to see that suggestions/comments in database (admin interface). After the comment is submitted, it is not saved in database. I have some mistake here but I don't know where it is. Can you please help me? views.py: def komentariPrijedlozi(request): if request.method == 'POST': form = CommentsSuggestionsForm(request.POST) if form.is_valid(): form.save() return render(request, 'rjecnik/successCommentsSuggestions.html') form = CommentsSuggestionsForm() context = {'form' : form} return render(request, 'rjecnik/komentariPrijedlozi.html', context) komentariPrijedlozi.html: <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Comments and suggestions</title> </head> <body> <section class="main-container1" style=" margin-top: 50px; background-color: lightgray;"> <div class="columns"> <div class="main-par" style="font-size: 21px; margin-bottom: 20px;">Komentari i prijedlozi novih prijevoda:</div> <div class="column is-half is-offset-one-quarter"> <form method="POST" autocomplete="off" enctype="multipart/form-data"> <tr> <th> <label for="suggestion1">Prijedlog novog pojma:</label> </th> <td > <input type="text" name="suggestion1" maxlength="100" autocomplete="off" style="width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block;"> </td> </tr> <tr> <th> <label for="suggestion2">Prijedlog prijevoda:</label> </th> <td> <input type="text" name="suggestion2" maxlength="100" autocomplete="off" style="width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block;"> </td> </tr> <tr> <th> <label for="comment">Komentar:</label> </th> <td> <textarea name="comment" cols="40" rows="10" style="width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block;"></textarea> </td> </tr> {% csrf_token %} … -
How to make Scrapy Request in Django view
I have to create a function or django view for making a scrapy Request to a URL and it will return response of that URL. -
Django : "matching query does not exist" on save() method
I'm building an application that fetches an API and fills a DB with the obtained data. I'm trying to save to DB for each JSON row processed. When I call obj_to_insert.save() at the end, I get an error: geotrek.trekking.models.DoesNotExist: POI matching query does not exist. POI is one of my models, it's correctly defined and imported. Here is the structure of the processing function (I oversimplified it, all the vars I use are correctly defined in the real code, etc.): with transaction.atomic(): for datatype_name, datatype_details in dict.items(): ##fetching the API r = response.json()["results"] for index in range(len(r)): dict_to_insert = {} for f in normal_fields: dict_to_insert[f.name] = other_dict['key'][f.name] obj_to_insert = DataType(**dict_to_insert) for f in fkeys_fields: fk_to_insert = {} if condition: fk_to_insert[f.name] = other_dict['key'][f.name] new_topo = Topology.objects.create(**fk_to_insert) obj_to_insert.topo_object = new_topo elif condition: obj_to_insert.structure = Structure.objects.get(name = AUTHENT_STRUCTURE) elif condition: fk_to_insert[f.name] = other_dict['key'][f.name] ##simplified setattr(obj_to_insert, fk_field, f.related_model.objects.get(**fk_to_insert)) obj_to_insert.save() Everything goes well until the final .save(), which gives the models.DoesNotExist error. It's as if Django gets the obj_to_insert, tries to find a corresponding row in DB and doesn't find it (normal: I'm trying to create it). When I print(vars(obj_to_insert)) just before trying to save, here is the output, which looks perfectly fine to me: … -
Repetition of the same letter
I need to received an error message if I have 3 consecutives identiques value for "PCR POS/Neg" , 3 times in my "output_df". exemple: P P P N P P P N N P P P I have here 3 results P consecutif, 3 times How i can do it ? from django.shortcuts import render from django.core.files.storage import FileSystemStorage import pandas as pd import datetime from datetime import datetime as td import os from collections import defaultdict from django.contrib import messages import re import numpy as np def home(request): #upload file and save it in media folder if request.method == 'POST': uploaded_file = request.FILES['document'] uploaded_file2 = request.FILES['document2'] if uploaded_file.name.endswith('.xls') and uploaded_file2.name.endswith('.txt'): savefile = FileSystemStorage() #save files name = savefile.save(uploaded_file.name, uploaded_file) name2 = savefile.save(uploaded_file2.name, uploaded_file2) d = os.getcwd() return render(request, "index.html") output_df['Date and Time'] = pd.to_datetime(output_df['Date and Time']) output_df['new'] = output_df["value"].apply(lambda x: ord(x)) np.floor(output_df["new"].diff().eq(0).sum() / 3) return output_df.to_html(), -
JS Alarmclock needs adjustment
I'm trying to set an alarmclock for the webapp I'm creating with Django. To do so, I followed some tutorials and adjusted the code for my needs and all. It works. My problem is, I want to set the time and date, manually, with the variables I get from Django views (I passed the hour and min variables into my HTML file). Here is my alarm.html file: {% extends 'mainapp_hf/base.html' %} {% block content %} {{ js_hour }} <div style="width: 100%; display: flex; justify-content: center; "> <div id="clock"></div> <script> const display = document.getElementById('clock'); const audio = new Audio('https://assets.mixkit.co/sfx/preview/mixkit-alarm-digital-clock-beep-989.mp3'); audio.loop = true; let alarmTime = null; let alarmTimeout = null; function updateTime() { const date = new Date(); const hour = formatTime(date.getHours()); const minutes = formatTime(date.getMinutes()); const seconds = formatTime(date.getSeconds()); display.innerText=`${hour} : ${minutes} : ${seconds}` } function formatTime(time) { if ( time < 10 ) { return '0' + time; } return time; } function setAlarmTime(value) { alarmTime = value; } function setAlarm() { if(alarmTime) { const current = new Date(); const timeToAlarm = new Date(alarmTime); if (timeToAlarm > current) { const timeout = timeToAlarm.getTime() - current.getTime(); alarmTimeout = setTimeout(() => audio.play(), timeout); setTimeout(clearAlarm, timeout + 5000); alert( value ); } … -
Add columns in model in DJango based on if else condition
This is my Django code for my model I want to have columns in the model based on the value of chart type enter column there` class DashboardCreativeQuery(models.Model): query_name = models.CharField(max_length=256, null=False, unique=True) query = models.TextField( null=False) chart_type = models.ForeignKey(DashboardCreativeCharts, blank=True, null=True, related_name='chart_type', on_delete=models.CASCADE) if chart_type: test= JSONField(null=False) How can I do it? -
how to use annotate before group by(values) : AttributeError: 'dict' object has no attribute 'annotate field' - django
I'm trying to calculate some fields then group a field, it raise this error : AttributeError: 'dict' object has no attribute 'total_prices' here is the query that i tried collections = Invoice.objects.filter( invoice__status=True).annotate( total_prices=Sum((F('price')) - F('discount'),output_field=DecimalField(max_digits=20,decimal_places=3)), paid_prices=Sum(F('cash')), total_discount=Sum(F('discount')), storage_prices=Sum( (F('item__mobile__price')+F('item__mobile__cost')),output_field=DecimalField(max_digits=20,decimal_places=3)), incomes=Case( When(total_prices__gte=F('storage_prices'),then=F('total_prices')-F('storage_prices')),default=0,output_field=DecimalField(max_digits=20,decimal_places=3)), loss=Case( When( storage_prices__gt=F('total_prices'),then=F('storage_prices') - F('total_prices')),default=0,output_field=DecimalField(max_digits=20,decimal_places=3)), num=Count('pk'), date_collections=TruncDay('item__mobile__collection__collection_date') ).values('date_collections').order_by('date_collections') for i in collections: print(i.total_prices) i dont want to put the group by before the annotate( i know it works, but not work as i want for the loss annotate) Thank you, most regards .. -
Shango management command update all empty value with integer 1
I have to make a command make all the blank values in integer 1. def handle(self, *args, **options): Soccer.objects.filter(goalblank=True).Update(goalblank=1) -
how to use integer value from for loop to get a list element in django template
I have a list of numbers in views.py list=[0,1,2,3,4,5] (it is not the same all the time I'm fetching it from API) then in my search.html I have written the following code:- {% for i in list %} <a href="https://example.com//{{ id[i] }}"> <img class="row_poster" src="https://this.isapi.org/{{poster[i]}}" alt="" /> <h4>{{title[i]}}</h3> </a> {% endfor %} where the id, poster, title are lists passed through views.py I want to get elements of each list 1 by 1 I tried adding for loop for each but the result was bad all posters render first and then titles were rendering I want to know how can I use it to call items from the list or any other by which I can access elements for all lists in a single loop. I have also tried {% with abcd=i %} but the result was the same keep getting this error Could not parse the remainder: '[i]' from 'id[i]' -
How to test mysql's max_execution_time option in django using pytest
I'm trying to test max_execution_time option of mysql in Django with pytest. But I'm having trouble with making slow query to test the option with pytest. Can you give me any tips or good example of slow query? Environment Python 3.8.10 Django 3.0.14 pytest 5.4.3 MySQL 5.7 Tried @pytest.mark.django_db def test_max_execution_time(): with pytest.raise(OperationalError): result = list(Blog.objects.raw(""" CREATE PROCEDURE InfLoop() BEGIN WHILE 1=1 DO SELECT 1; END WHILE; END; CALL InfLoop(); """)) pytest test.py Actual FAILED test.py F ===================================================================================== FAILURES ====================================================================================== ______________________________________________________________________ test_max_execution_time _______________________________________________________________________ @pytest.mark.django_db def test_max_execution_time(): with pytest.raises(OperationalError): > result = list(Blog.objects.raw(""" CREATE PROCEDURE InfLoop() BEGIN WHILE 1=1 DO SELECT 1; END WHILE; END; CALL InfLoop(); """)) E Failed: DID NOT RAISE <class 'django.db.utils.OperationalError'> test.py:102: Failed ============================================================================== short test summary info ============================================================================== FAILED test.py::test_max_execution_time - Failed: DID NOT RAISE <class'django.db.utils.OperationalError'> Expected 1 passed -
Django JWT graphql auth can not detect the logged in user
I have implemented jwt with graphql in django using django-graphql-jwt. I have graphql django userType as : class UserType(DjangoObjectType): class Meta: model = User fields = ('id', 'username', 'email','first_name','last_name', 'is_active') and have use the tokenAuth for logging the user in. The mutation schema is: class Mutation(graphene.ObjectType): token_auth = graphql_jwt.ObtainJSONWebToken.Field() refresh_token = graphql_jwt.Refresh.Field() verify_token = graphql_jwt.Verify.Field() schema = graphene.Schema(query=Query, mutation=Mutation) and I call it by this query and get the response successfully: mutation loginUser( $email: String!, $password: String!) { tokenAuth( email: $email, password: $password) { token refreshToken payload } } The verifyToken query also works successfully when I call it and put the returned token in my query variables: mutation VerifyToken($token: String!) { verifyToken(token: $token) { payload } } But When I want to get the logged in user in a query, Django does not detect it. The query class is implemented as: class Query(graphene.ObjectType): #other stuff profile = graphene.Field(UserType) #other resolvers def resolve_profile(root, info, **kwargs): user = info.context.user #This line always prints "AnonymousUser" print(user) jwt_payload_handler = jwt_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = jwt_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) #This line does not print anything (print is not called). probably because the process had an exception in above lines print("Token is ", token) … -
How to modify existing model instance in django?
In Django, I am trying to modify the title of the existing book with id. My views.py file consists of b=Books.objects.filter(book_id__iexact=book) b.title = "Narnia" b.save() I am getting error and unable to save the model instance. -
How to delete a json row if all row is zero?
I have complex JSON data and I am creating a table from this data. I can get all values clearly. But I want to remove or hide a row if all data is zero. In my case, if my counter is 5 then I should remove 'title' and 'values' I created a function for that but I cannot remove the line. How can I do it? for data1 in financial_balance: for data2,key in data1.items(): if isinstance(key, str) != True: for k in key: for l,d in k.items(): if isinstance(d, str) != True: for x in d: count1 = 0 counter = 0 for e in x["values"]: count1 += 1 if e["value"] == 0: counter += 1 if counter == 5: # remove row my data: [ { 'name': 'Balance Sheet', 'dataList': [ { 'mainEntry': 'Assets', 'titles': [ { 'title': 'Trade', 'values': [ { 'yea r': 2020, 'value': 268057, 'colorCode': None }, { 'year': 2019, 'value': 421621, 'colorCod e': None }, { 'year': 'Year over year trends 2019 vs 2020', 'value': -0.36, 'colorCode': None }, { 'year': 'Common Size Analysis 2020', 'value': 0.12, 'colorCode': None }, { 'year': 'Common Size Analysis 2019', 'value': 0.14, 'colorCode': None } ] }, { 'title': … -
Validate model field in single line
approximation = models.IntegerField(null=False, default=None) I need to validate this field. It should be greater than 0 but i don't want to make function. -
How do I delete a record in django_admin_log?
So I have been making some (big) changes in my User model, and somehow got this error : django.db.utils.IntegrityError: The row in table 'django_admin_log' with primary key '1' has an invalid foreign key: django_admin_log.user_id contains a value '1' that does not have a corresponding value in member_user.id. The cause of the error is the superuser I created. But then I changed my User model from Django's built-in model to custom model.I'm trying to delete the record from the table django_admin_log which has user_id equal to 1. How do I do this? Thanks in advance. -
Django - Serving production using Apache2
Days I struggle with this. I have a django webapp written in Python 3.10 that works fine when launched using pipenv shell then python3.10 manage.py runserver. Also, doing python3.10 app/wsgi.py quits without any error. Now I want it to be served by Apache2. Here is my conf file: Listen 8000 <VirtualHost *:8000> ServerAdmin webmaster@localhost DocumentRoot /opt/app ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined LogLevel Debug Alias /static /opt/app/static <Directory /opt/app/static> Require all granted </Directory> <Directory /opt/app/app> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /opt/app/app/wsgi.py WSGIDaemonProcess app python-home=/opt/app python-path=/opt/app/app:/usr/local/lib/python3.10:/usr/local/lib/python3.10/lib-dynload:/usr/local/lib/python3.10/site-packages WSGIProcessGroup app </VirtualHost> Results in HTTP 500 when navigating to my website. Apache2 error logs: [core:notice] AH00094: Command line: '/usr/sbin/apache2' [wsgi:info] mod_wsgi (pid=25232): Attach interpreter ''. [wsgi:info] mod_wsgi (pid=25232): Adding '/opt/app/app' to path. [wsgi:info] mod_wsgi (pid=25232): Adding '/usr/local/lib/python3.10' to path. [wsgi:info] mod_wsgi (pid=25232): Adding '/usr/local/lib/python3.10/lib-dynload' to path. [wsgi:info] mod_wsgi (pid=25232): Adding '/usr/local/lib/python3.10/site-packages' to path. [wsgi:info] [remote 192.168.3.110:37296] mod_wsgi (pid=25232, process='app', application=''): Loading Python script file '/opt/app/app/wsgi.py'. [wsgi:error] [remote 192.168.3.110:37296] mod_wsgi (pid=25232): Failed to exec Python script file '/opt/app/app/wsgi.py'. [wsgi:error] [remote 192.168.3.110:37296] mod_wsgi (pid=25232): Exception occurred processing WSGI script '/opt/app/app/wsgi.py'. [wsgi:error] Traceback (most recent call last): [wsgi:error] File "/opt/app/app/wsgi.py", line 13, in <module> [wsgi:error] from django.core.wsgi import get_wsgi_application [wsgi:error] File "/usr/local/lib/python3.10/site-packages/django/__init__.py", line 1, … -
How to use select_related or prefetch_related with @property?
I have a model with a custom property: class Product(models.Model): name = models.CharField(_('Name'), max_length=255) [...] @property def price(self): return (self.price_line_product.filter(table__standard=True, table__client=self.client) .first().price) The price property will look in another table for the right data. price_line_product is the related_name to access it. It works fine but I have a lot of SQL queries that are executed. I tried in my view to add prefetch_related: Product.objects.filter(deleted=False).prefetch_related('price_line_product') Django doesn't return any error but it doesn't change the number of requests. How to force the ORM not to make duplicate requests? -
Django Model - How to set up ManytoMany, foreign key relation
I am trying to create a model, where an individual can have multiple roles in multiple firms. like a firm can assign an individual to Director and MD Roles, as well as Director role can be given to two separate individuals. an individual can have multiple roles in multiple Firms like MD in FirmA and Directors & MD in FirmB. I have three models, Firm, Individual and FirmRole. How can I achieve this? -
How To save Pdf to Excel file in Django
I have a Doubt How to save pdf file to Excel File : Here My Code Is : I Have Pdf File Need to Extract Some text In The Pdf File to Excel , What Actually I needed Is Need to Upload Pdf File in Template And Download , Need to Render the Pdf File And Save Into My Database And Retrieve To Next template As Download File Here My Code Is : def index(request): if request.method == 'POST': form = MyfileUploadForm(request.POST, request.FILES) if form.is_valid(): name = form.cleaned_data['file_name'] the_files = form.cleaned_data['files_data'] print(the_files) my_dataframe = pd.DataFrame() with pdfplumber.open(the_files) as pdf: for page in pdf.pages: text = page.extract_text().splitlines() nameIdx, add1Idx, add2Idx, add3Idx, ShipmentIdx, WaybillIdx, phoneIdx = -1, -1, -1, -1, -1, -1, -1 print('vikram2') for idx, line in enumerate(text): if "Shipment Reference :" in line: ShipmentIdx = idx if "Waybill Number : " in line: WaybillIdx = idx if "Invoice Number :" in line: nameIdx = idx - 1 if "Receiver :" in line: add1Idx = idx + 4 if "Receiver :" in line: add2Idx = idx + 6 if "Receiver :" in line: add3Idx = idx + 7 if "Tax ID :" in line: phoneIdx = idx - 1 textIdx = … -
Wrong SQL is generated when querying Array of Datetime field in Django
I have a model where I am storing datetime in Array Field. Now when I am using this Array field in F expression this is giving me SQL error. On Printing the SQL I can see that wrong SQL is being Generated. Here is the Sample MOdel Structure : class MyModel(models.Model): valid_date = models.DateTimeField(default=timezone.now) exclude_dates = ArrayField( models.DateTimeField(_("Exclude dates"), null=True, blank=True), null=True, blank=True ) Now When I will query this model to give me all records but ignore those Dates who are in exclude_dates list. qs = MyModel.objects.exclude(valid_date__range=F('exclude_dates')) This above ORM will raise psycopg2.errors.SyntaxError. if you will check resultant SQL by print(qs.query). You will find out that wrong SQL is being generated somehow. I am struggling to find out the reason of same and not able to think about the alternative solution.