Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Profile() got an unexpected keyword argument 'user' while extending django's User model
Here I have extended django's user model with profile model and i want to add this fields to user model. Following are the files. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user_ref = models.OneToOneField(User, on_delete=models.CASCADE) pr1_points = models.IntegerField(default=0) pr2_points = models.IntegerField(default=0) @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): user = instance if created: profile = Profile(user=user) profile.save() @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() register function in views.py is as follows : ''' def postregister(request): if request.POST: first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') email = request.POST.get('email') username = request.POST.get('username') password1 = request.POST.get('password1') password2 = request.POST.get('password2') if password1 == password2: if User.objects.filter(username=username).exists(): messages.error(request, 'Username is Taken Please Try Again') return render(request,'signup.html') elif User.objects.filter(email=email).exists(): messages.error(request, 'Email is Taken Please Try Again') return render(request,'signup.html') else: user = User.objects.create_user(username=username, first_name=first_name, last_name=last_name, email=email, password=password1) user.save() print('You are registered successfully, Please sign to continue.') return redirect('login') else: messages.error(request, 'Password is not matching Please Try Again') return render(request,'signup.html') else: return redirect('register') ''' so while creating new user it is giving error as: Profile() got an unexpected keyword argument 'user'. SO please anyone know the answer help me with this. -
Django pass a url kwarg into a form.Form
I'm trying to get initial values for a form.Form class form from url. urls.py path('nueva/<client_id>/', new_check_view, name='nueva valoración'), views.py def new_check_view(request, client_id): my_form = NewCheckForm() # print (client_id) if request.method == "POST": my_form = NewCheckForm(request.POST) if my_form.is_valid(): Check.objects.create(**my_form.cleaned_data) else: print(my_form.errors) context = { "form": my_form } return render (request, 'checks/new-check.html', context) forms.py class NewCheckForm(forms.Form): user_id = forms.ModelChoiceField( label='Nombre', queryset= Client.objects.all(), initial=client_id, ) However, I don't get how to pass that kwargs from the view to the class form. -
update view don't save the bank
I wanted to know how I do it here to update this form in the bank, I am using 2 forms with different models and every time I try to save the information they are not exchanged and I get an invalid form error. class PacienteUpdateView(UpdateView): queryset = Endereco_pacientes.objects.all().select_related('cpf') form_class = PacientesModelForm second_form_class = EnderecoPacientesModelForm template_name = 'pacientes/pacientesForm.html' #get_success_url = '.' def get_context_data(self, **kwargs): context = super(PacienteUpdateView, self).get_context_data(**kwargs) context['form'] = self.form_class(instance=self.object.cpf) context['form2'] = self.second_form_class(instance=self.object) print(context['form']) return context I can already display the information in HTML, but I cannot update I thank the attention -
Django Management Command Generating Model Entries Corrupts File if File Is the Same on Each Entry
I have a custom management command in Django that generates an email to be added to the "django-mail-queue" app MailerMessage model. This tool reads from an existing table for information. However I am having issues with attachments where the first one, the attachment is fine, but the second one the attachment is corrupted. My belief is that Django is queuing up all the SQL commands and executing them all at once and thus reading the attachment file all at the same time for every entry. I think this is causing a race condition that is corrupting the second attachment. This is the code for send_to_user in send_to_users: msg = MailerMessage() msg.subject = campaign.subject msg.from_address = from_address msg.to_address = send_to_user.email msg.html_content = f"some content" # ATTACH THE ATTACHMENTS if attachments: for attachment in attachments: msg.add_attachment(attachment=attachment.file_attachment) msg.save() How do I get it to save directly without causing this race condition? Shouldn't msg.save() save to the database right away at the end of the for loop and then process the next one? -
Convert Base64 format Images to single pdf file and store it to django model
I have several images in data: format I need to convert them into a single pdf file in landscape mode and store them in Django model filefield. How can I achieve this in Python? -
How do I fitler the intial table using django-tables2 and django-filter?
I'm using django-tables2 and django-filter to list employees from a model. I'm having trouble filtering the initial table rendered. It's including all records. I want the initial table to only include employees where status=1. Then, have the filter take over. views.py from .models import Employee from .tables import EmployeeTable from .filters import EmployeeFilter from .forms import EmployeeSearchForm class EmployeeListView(SingleTableMixin, FilterView): model = Employee table_class = EmployeeTable template_name = 'employees/employee_list.html' filterset_class = EmployeeFilter def get_table_data(self): return Employee.objects.filter(status=1) filters.py: from django.db.models import Value, Q from django import forms from .models import Employee class EmployeeFilter(django_filters.FilterSet): search = django_filters.CharFilter(label='Search', method='search_filter') inactive = django_filters.BooleanFilter(widget=forms.CheckboxInput, label='Inactive', method='include_inactive') def search_filter(self, queryset, name, value): return queryset.annotate(fullname=Concat('first_name', Value(' '), 'last_name')).filter( Q(fullname__icontains=value) | Q(g_number__icontains=value) ) def include_inactive(self, queryset, name, value): expression = Q(status__in=[1,2,5]) if value else Q(status__in=[1,5]) return queryset.filter(expression) class Meta: model = Employee fields = ['search', 'inactive'] tables.py: from django.utils.html import format_html from django.urls import reverse import django_tables2 as tables from .models import Employee class EmployeeTable(tables.Table): full_name = tables.Column(order_by=("first_name", "last_name")) g_number = tables.Column(linkify=True) selection = tables.columns.CheckBoxColumn( accessor='pk', attrs = { "th__input": {"onclick": "toggle(this)"}}, orderable=False ) term = tables.Column(verbose_name=("Action"), empty_values=()) class Meta: model = Employee template_name = "django_tables2/bootstrap.html" fields = ("selection", "g_number","full_name", 'org', 'job', 'status', 'term') attrs = { "class": … -
Zappa project and virtualenv have the same name
When running zappa deploy dev I get this error: Warning! Your project and virtualenv have the same name! You may want to re-create your venv with a new name, or explicitly define a 'project_name', as this may cause errors. Would renaming virtualenv be a safer route or renaming the project? How do I define a project_name explicitly? -
How to display a queryset object name rather than a queryset object itself in Django?
Registered users of my app can create and delete expense tracking sub-accounts. When deleting, they get to pick which account to delete: The above image shows the current choices. I would like to display the name of the account, rather than the object which the name is referring to, but how? forms.py class UdaForm(forms.Form): # User Deleted Account Form def __init__(self, *args, user, **kwargs): super().__init__(*args, **kwargs) self.user = user self.fields['UDA_name'].queryset = UserMadeAccount.objects.filter(UMA_user=user) UDA_name = forms.ModelChoiceField(label="Account", queryset=UserMadeAccount.objects.all()) views.py def user_accounts(request, user_id): if request.user.is_authenticated: # Get all accounts of user by matching user_id user_made_accounts = specific_umacs(user_id) user_data = [i for i in user_made_accounts] if "UMA_form_name" in request.POST: if request.method == 'POST': uma_form = UmaForm(request.POST) uda_form = UdaForm(user=request.user) if uma_form.is_valid(): # Adds new user made account to the DB add_uma(uma_form, request.user) # Get all accounts of user by matching user_id user_made_accounts = specific_umacs(user_id) user_data = [i for i in user_made_accounts] return render(request, 'user_accounts.html', {"uma_form": uma_form, "uda_form": uda_form, "user_data": user_data}) if "UDA_name" in request.POST: if request.method == 'POST': uda_form = UdaForm(request.POST, user=request.user) uma_form = UmaForm() if uda_form.is_valid(): # Delete user made account from DB delete_uma(uda_form=uda_form, user_obj=request.user) # Get all accounts of user by matching user_id user_made_accounts = specific_umacs(user_id) user_data = [i for i in … -
Is it ok to include root django app in list of apps in settings
Say I create a django project called: recipes can I include that core folder (not a proper django app i think, with urls and core things) in my list of INSTALLED_APPS = [ 'recipes' ] This is so I can put things like management commands in a centralised place, rather than having to have an app called home or core, as I like to do normally. It seems to work are there any drawbacks with this? -
How to properly use front-end technologies liker webpack with Django?
We have a Django project using Bootstrap. I think this is common. Now I'm looking at adding more javascript functionality, e.g., hotkeys. Two options are Download the jquery plugin and load it directly using Django's static tag. I've set up ManifestStaticFilesStorage that does cache-busting on static assets. Set up a front-end technology stack: npm (or yarn), load my own jquery and bootstrap, likely compile it with Webpack. And .. rip out ManifestStaticFilesStorage because Webpack also does cache-busting? I'm not sure. Wouldn't that also break Django's static tag? I've read many different posts now, and the Django and front-end communities mostly seem to ignore each other. Maybe django-npm is the answer? How do people manage front-end assets in Django? -
Is there any function in python or can we create it in which we can give input (string) and in return output (dictionary)?
I am using OCR to read invoice from pdf and able to extract them in string format. now i want to store in Json format in Database. below is input in which i am able to extract key and value by: keys_=["None" if x == '' else x for x in unclean_data[2].lower().split(',')] print(keys_) key_: ['units ', 'item code ', 'description ', 'unit price (inc-gst) ', 'discount % ', 'total (inc-gst) ', 'None'] values_=["None" if x == '' else x for x in unclean_data[3].lower().split(',')] print(values_) value_: ['31.68 ', 'vhc ', 'amstel blanco 60x120 ', '$39.60 ', 'None', '$1', '254.53 ', 'None'] now using res_two = dict(zip(key_,values_) i am able to convert it, but i want to search key using regular expression in input and replace it with the keys show in the output. example **enter code here** "Item_Code","Description","Quantity","Unit_price_ex_GST","Value_ex_GST","GST","Discount%","Total(Inc_GST)" Input = Table: Table_1 Units ,Item Code ,Description ,Unit Price (inc-GST) ,Discount % ,Total (inc-GST) , 31.68 ,VHC ,Amstel Blanco 60x120 ,$39.60 ,,$1,254.53 , 1 ,D0001 ,Delivery Charge ,$145.00 ,,$145.00 , Expected Output = { "Item_Code":"VHC", "Description":"Amstel Blanco 60x120", "Quantity":3, "Unit_price_ex_GST":$39.60 , "Value_ex_GST":40.91, "GST":'', "Discount%":'', "Total(Inc_GST)":$1,254.53 }, -
Hot to display latest saved image from django form?
i'm uploading image in my django form and and displaying them all at same time. I want to know how to display latest image after submitting that form. Any help would be appreciated. models.py class Upload(models.Model): image = models.ImageField(upload_to='images') action = models.CharField(max_length=50, choices=CHOICES) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) forms.py class UploadModelForm(forms.ModelForm): class Meta: model = Upload fields = [ 'action', 'image' ] views.py def picture_create_view(request, pk=id, *args, **kwargs): if request.method == 'POST': form = UploadModelForm(request.POST, request.FILES) if form.is_valid(): form.save() context = {'form':form,'up':Upload.objects.order_by('-pk')[0]} return render(request, 'upload.html', context) else: form = UploadModelForm() return render(request, "upload.html", {"form": form}) I think problem is with line in views.py context = {'form':form,'up':Upload.objects.order_by('-pk')[0]} upload.html {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> {%for i in up %} <img src ="{{i.image.url}}", alt=""> {%endfor%} {% endblock %} I know code in upload.html also have to change with views.py any suggestion will be appreciated also. I'm using neural network with image field and i'm sure it works correctly. I cant paste that code here. -
split a QuerySet in sublists/subsets
I am running a QuerySet that returns a list resembling this: {'name': 'A', 'month': datetime.datetime(2020, 1, 1, 0, 0), 'avg': 316.684} {'name': 'A', 'month': datetime.datetime(2020, 2, 1, 0, 0), 'avg': 316.643} {'name': 'A', 'month': datetime.datetime(2020, 3, 1, 0, 0), 'avg': 301.835} ... {'name': 'B', 'month': datetime.datetime(2020, 1, 1, 0, 0), 'avg': 316.684} {'name': 'B', 'month': datetime.datetime(2020, 2, 1, 0, 0), 'avg': 316.643} {'name': 'B', 'month': datetime.datetime(2020, 3, 1, 0, 0), 'avg': 301.835} ... {'name': 'C', 'month': datetime.datetime(2020, 1, 1, 0, 0), 'avg': 316.684} {'name': 'C', 'month': datetime.datetime(2020, 2, 1, 0, 0), 'avg': 316.643} {'name': 'C', 'month': datetime.datetime(2020, 3, 1, 0, 0), 'avg': 301.835} Generated this way: Entries.objects .annotate(month=TruncMonth('date')) .values('name', 'month') .annotate(avg=Avg('value')) .order_by('name') So basically I have 12 entries per name, one per month. I was wondering if it was possible, via query, returning: [ 'A': { 'month': datetime.datetime(2020, 1, 1, 0, 0), 'avg': 316.684, 'month': datetime.datetime(2020, 2, 1, 0, 0), 'avg': 316.684, 'month': datetime.datetime(2020, 3, 1, 0, 0), 'avg': 316.684, }, 'B': { 'month': datetime.datetime(2020, 1, 1, 0, 0), 'avg': 316.684, 'month': datetime.datetime(2020, 2, 1, 0, 0), 'avg': 316.684, 'month': datetime.datetime(2020, 3, 1, 0, 0), 'avg': 316.684 }, ... ] or if the only way is to create another object … -
integration of a guacamole client into a django site
I would like to ask for help regarding the development of a guacamole client within a django site. Unfortunately, not being exactly an expert on the subject, I don't know if it is actually possible and looking on the internet I had no luck. With django it is possible to execute javascript code, so I believe there is a way. I have read the user manual on the Guacamole website, in particular the procedure explained in "Chapter 27. Writing your own Guacamole application" (http://guacamole.apache.org/doc/gug/writing-you-own-guacamole-app .html), however, I do not understand if it is a solution strictly achievable with the tools listed in the guide or if in some way it is possible to achieve the same thing in different environments. I have no obligations regarding the method or tools to use, so I am open to all solutions, even the most imaginative. Thanks in advance -
django.db.utils.OperationalError: no such column: users_student.user_id
Is there any error in the student's model? I am unable to add a student in the admin site. I got this error after adding this student model. No issue with the one-to-one field in the Student model. I do have id in the user model Models.py class User(AbstractUser): CATEGORY_CHOICES= [ ('STUDENT','STUDENT'), ('TEACHER' ,'TEACHER') ] name = models.CharField(max_length=100) email = models.EmailField(max_length=100, unique=True) password = models.CharField(max_length=100) category = models.CharField(max_length=100, choices= CATEGORY_CHOICES,default='STUDENT') registrationDate=models.DateField("RegistrationDate", auto_now_add=True) profile_pic=models.ImageField(default='default.png',blank=True) USERNAME_FIELD= 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.email class Student(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key= True) study_class = models.IntegerField() bio = models.TextField(blank=True) Traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/users/student/add/ Django Version: 3.1.7 Python Version: 3.9.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'users'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\KAVYA\Documents\Test-series-demo\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\KAVYA\Documents\Test-series-demo\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute return Database.Cursor.execute(self, query, params) The above exception (no such column: users_student.user_id) was the direct cause of the following exception: File "C:\Users\KAVYA\Documents\Test-series-demo\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\KAVYA\Documents\Test-series-demo\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\KAVYA\Documents\Test-series-demo\venv\lib\site-packages\django\contrib\admin\options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, … -
Dynamic django forms from JSON field
My department model has a JSON field (see the example below). I am trying to create a Django form for an inventory item which will change depending on the user-chosen department. This means I want my form to change and render data from the given JSON field. Also, read rules, like, is required or not, is a checkbox or not, and render appropriately. I have no idea how to achieve this goal. Chances are, it's manageable, but I need a solid lift. Thanks in advance { "make": { "type": "ckeditor", "label": "Make", "rules": "required" }, "model": { "type": "ckeditor", "label": "Model" }, "title": { "type": "ckeditor", "label": "Title", "rules": "required" }, "colour": { "type": "ckeditor", "label": "Colour" }, "year_age": { "type": "ckeditor", "label": "Year/ Age" }, "body_type": { "type": "select2", "label": "Body Type", "options": [ { "key": "Automatic", "value": "automatic" }, { "key": "Manual", "value": "manual" }, { "key": "Semi-automatic", "value": "semi_automatic" } ] }, "condition": { "type": "select2", "label": "Condition", "options": [ { "key": "New", "value": "new" }, { "key": "As New", "value": "as_new" }, { "key": "Excellent", "value": "excellent" }, { "key": "Good", "value": "good" } ] }, "dimensions": { "type": "ckeditor", "label": "Dimensions" }, "vin_number": { "type": … -
wagtailmenus packages not working or rendering any thing in the template
I'm trying to access the wagtailmenus items {% load menu_tags %} {% load wagtailcore_tags %} <ul class="nav navbar-nav"> {% for item in menu_items %} {{ item.text }} {% endfor %} </ul> it is not displaying anything my home/models.py is class CustomFlatMenuItem(AbstractFlatMenuItem): """A custom menu item model to be used by ``wagtailmenus.FlatMenu``""" menu = ParentalKey( 'wagtailmenus.FlatMenu', on_delete=models.CASCADE, related_name="custom_menu_items", # important for step 3! ) image = models.ForeignKey( get_image_model_string(), blank=True, null=True, on_delete=models.SET_NULL, ) hover_description = models.CharField( max_length=250, blank=True ) # Also override the panels attribute, so that the new fields appear # in the admin interface panels = ( PageChooserPanel('link_page'), FieldPanel('link_url'), FieldPanel('url_append'), FieldPanel('link_text'), ImageChooserPanel('image'), FieldPanel('hover_description'), FieldPanel('allow_subnav'), ) and I added {% main_menu template="menu/main_menu.html" %} in the template that I want to view -
No installed app with label 'emp' Django and what i dont understand is that i did put the app in the installed apps
No installed app with label 'emp' Django and what i dont understand is that i did put the app in the installed apps this is the insstalled apps part -
What is the point of a Django Through Model?
I'm struggling to understand why I should use a relationship between 2 models w/ a "through" model vs just a model w/ foreign-keys to the 2 models. Here is some code: class Team(models.Model): name = models.CharField(max_length=100) class Person(models.Model): name = models.CharField(max_length=100) teams = models.ManyToManyField(Team, related_name="people", through="Membership") class Membership(models.Model): person = models.ForeignKey(Person, related_name="memberships") team = models.ForeignKey(Team, related_name="memberships") join_date = models.DateTimeField(auto_add_now=True) Given the above classes, I can do >>> bob = Person(name="Bob) >>> lakers = Team(name="Lakers") >>> bob.teams.add(lakers) And that will have the effect of creating a new Membershp instance linking "bob" and "lakers" w/ the correct "join_date". But I could also just do: >>> Membership.objects.get_or_create(person=bob, team=lakers) or even: >>> bob.memberships.add(lakers) And it would have the same effect, wouldn't it? So why should I bother having the "teams" m2m field from Person to Teams? Thanks -
Common Fields For Different Model in django rest framework
I am developing a system where I have created multiple types of users(seller, agent provider, buyer, etc) by extending the Django default user model (BaseUserManager). I need to create a common Address model which can be associated with all users. For example buyer, seller can be used the same address field but the data will be different & I need to post the user information and address field during the registration. I have tried the manytomanyfield but it's not working. Need an idea about the common model for all users. -
How to calculate fft using rest api in django, by using the csv file passed by the user using POST request
I have a code that take in post request from the server ie, a file and store it into my local drive. What I am looking to solve is to read the file uploaded and store it into the db.sqlite3 database, and pass a post request using rest api to perform fast fourier transform calculations on the csv data that the user upload. Using rest api only. I have created a api to get the file from the user, I am not able to find out a relavent solution regarding the issue, thanks for the help in advance. the csv file uploaded is this: time, amplitude, 0,0.73904, 0.02441,1.2372, 0.04883,1.0019, 0.07324,0.50924, 0.09766,-0.603, 0.12207,-1.6674, 0.14648,-1.5332, 0.1709,-0.85486, 0.19531,0.3971, 0.21973,1.3604, 0.24414,1.8384, 0.26855,1.7446, 0.29297,0.73904, 0.31738,-0.69308, 0.3418,-1.6969, 0.36621,-1.6215, 0.39063,-0.97252, 0.41504,-0.07721, 0.43945,0.78132, . . . There are 2549 lines in total Here is my model.py file from django.db import models class Files(models.Model): file = models.FileField(blank = False, null = False) remark = models.CharField(max_length = 50) timestamp = models.DateTimeField(auto_now_add=True) serializers file from rest_framework import serializers from . models import Files class FilesSerializer(serializers.ModelSerializer): class Meta(): model = Files fields = ('file', 'remark', 'timestamp') this is the view file from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response … -
Disable sentry logs
I have sentry in my django application. And sentry all the time print in the console [sentry] DEBUG: Discarding transaction because sampled = False [sentry] INFO: Discarded session update because of missing release How can I disable this messages and why they appers? This is how sentry is installed in django sentry_sdk.init( dsn=os.environ.get('SENTRY_DSN_PYTHON'), integrations=[DjangoIntegration(), CeleryIntegration()], debug=False ) -
Django rest create user if login not exists
My problem: I send post request from frontend, which consists of login and password. At backend (Django) I need to check if user with that login exists. And then send response back to frontend. I found different solutions, using different django rest decorators, but when i send post request, I get 500 error. serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' views.py: class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() And my js file, where I send post request: const register = () => { Axios.post('http://localhost:8000/api/users/', { login: loginReg, password: passwordReg, }).then((response) => { console.log(response); }) } -
Partially updating a model with BooleanFields with djangorestframework
I have a model like this class Status(models.Model): is_working = models.BooleanField( default=None, null=True ) is_at_home = models.BooleanField( default=None, null=True ) with the corresponding serializer class StatusSerializer(ModelSerializer): class Meta: model = Status fields = [ "is_working", "is_at_home" ] using the default ModelViewSet class StatusViewSet(viewsets.ModelViewSet): """ """ serializer_class = StatusSerializer queryset = Status.objects.all() Whenever I partially update a Status, by e.g calling the put method on the API, all other fields are reset to False instead of keeping their old value. Say, I have a Status that looks like this: { "id": 1, "is_working": null, "is_at_home": null, } If I call put using the following JSON: { "is_working": true } my data now looks like this { "id": 1, "is_working": true, "is_at_home": false <-- GOT UPDATED } I however, just want to update the is_working field, so that my desired result would be: { "id": 1, "is_working": true, "is_at_home": null } This probably has to do with the fact that HTML forms don't supply a value for unchecked fields. I, however, don't use any HTML forms as I'm purely consuming the API through JSON requests. Using the serializer as is, I'd need to perform an extra get request prior to updating the … -
Django ORM Query index usage on PSQL
Im a bit confused by the way how indexes are used when making Django ORM Queries. I have a PSQL Database with 12000 rows and a hash index on the column where I query against: SELECT * FROM numbertable WHERE number='77885'; With EXPLAIN ANALYZE of this query I can see a processing time of: Planning Time: 0.388 ms Execution Time: 0.203 ms When I do the equivalent Django ORM query like: numbertable.objects.filter(number='77885') in the Django shell_plus with --print-sql, I get an execution time which differs between 1,5 and 3 ms If I do an EXPLAIN ANALYZE on the SQL equivalent to the ORM query, which I got from the --print-sql, in the psql terminal SELECT "numbertable"."number", "numbertable"."id", FROM "numbertable" WHERE "numbertable"."number" = '77885' LIMIT 21; I get similar times to the first SQL Query: Planning Time: 0.428 ms Execution Time: 0.366 ms The Django model: from django.contrib.postgres.indexes import HashIndex class numbertable(models.Model): id = models.IntegerField(blank=True, null=True) number = models.CharField(max_length=5, blank=True, null=True, db_index=True) class Meta: managed = False db_table = 'numbertable' indexes = [ HashIndex(fields=['plz'], name='plz_town_index'), ] (the 'managed = False' comes from inspectdb which I had to use because I created the databasetable not through a django migration) I looked what …