Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django self.model.DoesNotExis
I have a user with a field set as None: None|Default User|07/07/2023 However, Django for some reason does not see it: queryset=Q(id=UUID(User.objects.get(user_id=None) ... raise self.model.DoesNotExist(pages.models.User.DoesNotExist: User matching query does not exist The closing parentheses are present. Setting the default field as another UUID present in the database as well isn't of any help. I am trying to run the migrations. My models: class User(models.Model): """ A class presenting user who can view lessons and have access to them """ user_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, null=True ) name = models.CharField(max_length=60, default='Name') date_of_registration = models.TimeField(default=timezone.now) def __str__(self): return self.id Setting the default to a present user_id doesn't help as well. Similar questions on stackoverflow were left without answers, no information about this particular problem in the Internet was found. What additional information should I provide? -
Insert data to sql databse using python django
I am trying to insert the form data to sql database. Can someone please check my code and help to find the error. def signup(request): print("Signup Started ") if request.method == 'POST': cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=PANKAJ\SQLEXPRESS;DATABASE=student_records') print("Database Object :- ",cnxn) #username = request.POST.get('username') #email = request.POST.get('email') cursor = cnxn.cursor() data = request.POST for key,value in data.items(): if key == 'username': name = value if key == 'email': email = value print('Username = ',name) print('Email = ',email) c ="insert into student values('{nm}','{em}')".format(nm=name,em=email) cursor.execute(c) cnxn.commit print("Data inserted sucessfully") return render (request,'signup.html') -
Can I see online users in Django using middleware?
I am making a website to learn Django and I am trying to make it possible to check who is online right now. I managed to do it using cookies, but I also have a desktop app that connects to the server and you can log in there as well, so users from the app were not shown as online. I saw a solution using sessions, so I might end up using it, but I have been learning about middleware and I am wondering if it would be possible to add a field to user model (last_activity) that would be updated by middleware everytime user sends a request to the server (so every time they go anywhere on the website). Then I would add a cut off time (5 minutes or something), and display it on a home page. The only issue is I am not good with middleware yet, and chatGPT suggested this: class ActivityMiddleware: def init(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) if request.user.is_authenticated: user = get_user(request) user.last_activity = datetime.now() user.save() return response But it only updates on logging in, do you know how to change it to update on any request? Thanks! Trying … -
Django objects.all() return empty queryset
I have a sqlite3 database that has pre-existing data(name, price, url, img,...). When i tried to print the value from objects.all() it return <QuerySet []> and loop through the list in templates return nothing My models class Product(models.Model): name = models.CharField(max_length=200) current_price = models.CharField(max_length=50) place = models.CharField(max_length=50) url = models.CharField(max_length=50) img = models.CharField(max_length=50) date_add = models.DateTimeField(default=timezone.now) def __str__(self): return self.name My urls: path("database", views.show_db, name="show_db") My views: def show_db(request): product_list = Product.objects.all() return render(request, 'product_list.html', {'product_list' : product_list}) My templates: {% block content %} {% for product in product_list %} <li> {{product.name}} </li> {% endfor %} {% endblock %} When i use dbshell to check, there is a scrape_product table(scrape is the name of the app): CREATE TABLE IF NOT EXISTS "scrape_product"( "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(200) NOT NULL, "current_price" varchar(50) NOT NULL, "place" varchar(50) NOT NULL, "url" varchar(50) NOT NULL, "img" varchar(50) NOT NULL, "date_add" datetime NOT NULL ); -
How to filter nested fields in a JSONField using Django ORM with Djongo?
I am working on a Django project where I am using Djongo as an ORM for MongoDB. I have a model named ProcessIDs which contains a JSONField named data. Within this JSONField, there are nested fields, and I am trying to filter the model entities based on a nested field value. Specifically, I am looking to filter based on the value of data->redirect_ids->status. I attempted to use the following query to filter the model entities: active_processes = ProcessIDs.objects.filter(data__redirect_ids__status__exact='active') I was expecting this query to return all ProcessIDs objects where the status field under redirect_ids nested within the data field is set to 'active'. However, executing this query resulted in a FieldError with the following message: FieldError: Unsupported lookup ‘redirect_ids’ for JSONField or join on the field not permitted. I am looking for a way to achieve the desired filtering using Django ORM with Djongo. Is there a specific syntax or method to filter based on nested field values within a JSONField in this setup? from djongo import models as mongo_models class ProcessIDs(mongo_models.Model): data = mongo_models.JSONField(max_length=1000, default=dict()) # ... other fields ... # Example object creation process = ProcessIDs.objects.create( data={'redirect_ids': {'ids': ['1234567', '7654321'], 'status': 'active'}, "category_type": "custom"} ) # Attempted query … -
Adding to cart Django
I'm trying to create a ecom website by Django and add products to cart, but when I run it didn't work. Can anyone help me? The codes goes here: models.py class Product(models.Model): category = models.ManyToManyField(Category, related_name='product', null=True) name = models.CharField(max_length=200, null=True) image = models.ImageField(upload_to="media", null=True) price = models.FloatField() quantity = models.IntegerField(default=0, null=True, blank=True) detail = models.TextField(max_length=1000, blank=False) digital = models.BooleanField(default=False, null=True, blank=False) def __str__(self): return self.name def get_absolute_url(self): return reverse("ecoshop:detail", kwargs={"pk": self.pk}) def get_add_to_cart_url(self): return reverse("ecoshop:add-to-cart", kwargs={"pk": self.pk}) def get_remove_from_cart_url(self): return reverse("ecoshop:remove-from-cart", kwargs={"pk": self.pk}) views.py def addtocart(request, pk): product = get_object_or_404(Product, pk=pk) order_item, created = OrderItem.objects.get_or_create(product=product, customer=request.user, order = False) order_qs = Order.objects.filter(customer=request.user, complete = False) if order_qs.exists(): order = order_qs[0] if order.items.filter(product__pk = product.pk).exists(): order_item.quantity += 1 order_item.save() messages.info(request, "Added quantity Item") return redirect("shop:cart", pk=pk) else: order.items.add(order_item) messages.info(request, "Item added to your cart") return redirect("shop:cart", pk=pk) else: date_order = timezone.now() order = Order.objects.create(customer=request.user, date_order=date_order) order.items.add(order_item) messages.info(request, "Item added to your cart") return redirect("shop:cart", pk=pk) def cart(request): if request.user.is_authenticated: customer = request.user order, created = Order.objects.get_or_create(customer = customer, complete = False) cartItem = order.get_cart_items items = order.orderitem_set.all() else: items = [] order = {'get_cart_items': 0, 'get_cart_total': 0} cartItem = order['get_cart_items'] categories = Category.objects.filter(is_sub=False) if request.user.is_authenticated: customer = request.user order, created … -
Django 4.2.5 System check identified no issues (0 silenced)
After reinstalled my app on another computer Want to change Python Version and update if necessary Librairies Eveything is ok for now (I had some issue with xhtmltopdf librairies with python 3.10 and more so for now I'm using 3.9 Python version) I run manage.py runserver ... But I've only got this message System check identified no issues (0 silenced). I tried to run with -v manage.py to have some details .. Nothing wrong on details I see some user who have this kind of issue and modify the 3306 port for mysql ... I did but still the same message. Is there any other solution ? Thanks for your help -
Remover link malicioso no site, encontrados pela Google Ads
Tenho um site, que desenvolvi com Django (python), html, css e javascript, hospedado no servidor pythonanywhere Ao tentar criar campanhas de anúncio no Google Ads com esse site, eles estão reprovando um anúncio por "software malicioso" Ao questionar a Google, ela respondeu que 3 links estão no site, e redirecionando os visitantes Links maliciosos: Https://betwinner1.com/pwapp Https://odnaknopka.ru/ Https://powered-by-revidy.com/ Porém eu já fiz diversas varreduras, e não encontrei nenhum desses links de redirecionando Onde no meu site, é possível esses links estarem sendo detectados pelo algoritmo da Google Ads, e como remover? Já procurei nos arquivos html, css e javascript, porém não encontrei esses links Não sei se a pythonanywhere é uma plataforma de hospedagem frágil Segue uma imagem com a resposta da Google Ads, explicando o porque reprova o site e os links maliciosos enter image description here -
Django product variation model - how to get distinct color
I am building a ecommerse store with django. One of the requirement is that a product can have a color and different sizes. I also want to keep track of the quantity of each size. I can create ProductVariation like product='test', size='small', color='red', quantity=5 , product='test', size='large', color='red', quantity=10. Now in db there are two objects created,how can I query that I only get color red in queryset when I am rendering product details. I looked at this example - Django Products model for e-commerce site but did not understand this bit - Color.objects.filter(productvariant__product=some_product).distinct() These are my models: class Product(models.Model): """ Product model to allow creating product records and linking with category """ product_uuid = models.UUIDField( default=uuid.uuid4, editable=False, unique=True) product_name = models.CharField(max_length=255) sub_category = models.ForeignKey( 'SubCategory', on_delete=models.CASCADE, related_name='products') product_description = models.TextField() is_featured = models.BooleanField(default=False) product_sku = models.CharField(max_length=255, null=True, blank=True) product_price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return self.product_name class Meta: verbose_name = 'Product' verbose_name_plural = 'Products' class ProductVariation(models.Model): """ ProductVariation model to allow creating product with different size and color """ product_var_uuid = models.UUIDField( default=uuid.uuid4, editable=False, unique=True) product = models.ForeignKey( 'Product', on_delete=models.CASCADE, related_name='product_variations') size = models.ForeignKey('Size', on_delete=models.CASCADE, related_name="product_sizes") color = models.ForeignKey('Color', on_delete=models.CASCADE, related_name="color") quantity = models .IntegerField() def __str__(self): return self.product.product_name … -
.ebextensions folder not included in my eb deploy method
The configuration for my static files in my django project are contained in my .ebextensions folder but during the deployment process it seems the folder is not being added to the EB environment. As a result my web app is not serving any static files when running from my ec2 instance. I've set up environment properties to include aws:elasticbeanstalk:environment:proxy:staticfiles in my elastic beanstalk configuration. I've checked to ensure my .ebextensions folder exists in my github. For some reason during deployment to EB the folder is being deleted / ignored. -
Django Mptt: filtering based on child category
I use django-mptt for Category model and I have Service model as well. The problem: I got all services associated to node category by clicking on a child category. What I want: I want to get all services associated to child category that I click. I believe I have to check it in an additional step in views (ServiceByCategoryListView). But I have no idea how to do that. Google doesn’t help me. models.py class Service(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255) description = models.TextField() preparation = models.TextField() price = models.CharField(max_length=10) available = models.BooleanField(default='True') category = TreeForeignKey('Category', on_delete=models.PROTECT, related_name='services') def __str__(self): return self.name class Category(MPTTModel): name = models.CharField(max_length=255, unique=True) parent = TreeForeignKey('self', on_delete=models.PROTECT, null=True, blank=True, related_name='children', db_index=True) slug = models.SlugField() class MPTTMeta: order_insertion_by = ['name'] class Meta: unique_together = [['parent', 'slug']] def get_absolute_url(self): return reverse('services-by-category', kwargs={'slug': self.slug}) urls.py urlpatterns = [ path('', CategoryListView.as_view(), name='category-list'), path('<slug:slug>/', ServiceByCategoryListView.as_view(), name='services-by-category'), ] views.py class CategoryListView(ListView): model = Category template_name = 'main/category_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['services'] = Service.objects.all() return context class ServiceByCategoryListView(ListView): model = Service context_object_name = 'services' template_name = 'main/service_list.html' def get_queryset(self): self.category = Category.objects.filter(parent=None).get(slug=self.kwargs['slug']) branch_categories = self.category.get_descendants(include_self=True) queryset = Service.objects.filter(category__in=branch_categories) return queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['name'] = self.category … -
The correct value is not saved in the database when I create an object in a Django project
I am writing a basic Django CRM project that is shared among organizations. When the superuser creates a new organization, he must set an organization name, organization owner and organization admin team. I am also attaching the relevant code: organization models.py class Organization(models.Model): name = models.CharField( max_length=255, unique=True, ) owner = models.OneToOneField( User, on_delete=models.CASCADE ) members = models.ManyToManyField( User, related_name='organizations', ) created_at = models.DateTimeField( auto_now_add=True ) updated_at = models.DateTimeField( auto_now=True ) def __str__(self): return self.name team models.py class Team(models.Model): name = models.CharField( max_length=255 ) created_by = models.ForeignKey( User, related_name='created_by', on_delete=models.CASCADE, ) organization = models.ForeignKey( Organization, on_delete=models.CASCADE ) created_at = models.DateTimeField( auto_now_add=True ) updated_at = models.DateTimeField( auto_now=True ) def __str__(self): return self.name user models.py class User(AbstractUser): username = None email = models.EmailField( _("email address"), unique=True, validators=[ validators.EmailValidator(), ] ) team = models.ForeignKey( 'team.Team', related_name='agents', null=True, blank=True, on_delete=models.CASCADE ) is_agent = models.BooleanField(default=True) is_org_owner = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email class Meta: verbose_name = 'CRM User' verbose_name_plural = 'CRM Users' view.py @login_required @superuser_access def add_organization(request): if request.method == 'GET': user_form = AddOrgOwnerForm() organization_form = AddOrganizationForm() team_form = AddTeamForm() else: user_form = AddOrgOwnerForm(request.POST) organization_form = AddOrganizationForm(request.POST) team_form = AddTeamForm(request.POST) if user_form.is_valid() and organization_form.is_valid() and team_form.is_valid(): … -
How to solve Key Error in views.py in Django
When I'm trying to fill out the form on the website, it throws me a Key Error. The status of POST http request is 500 and data don't save in db. Here is views.py file: @csrf_exempt def bookings(request): if request.method == 'POST': data = json.load(request) exist = Reservation.objects.filter(reservation_date=data['reservation_date']).filter( reservation_slot=data['reservation_slot']).exists() if exist==False: booking = Reservation( name=data['first_name'], phone_number=data['phone_number'], email=data['email'], reservation_date=data['reservation_date'], reservation_slot=data['reservation_slot'], ) booking.save() else: return HttpResponse("{'error':1}", content_type='application/json') date = request.GET.get('date',datetime.today().date()) bookings = Reservation.objects.all().filter(reservation_date=date) booking_json = serializers.serialize('json', bookings) return HttpResponse(booking_json, content_type='application/json') This is models.py: class Reservation(models.Model): name = models.CharField(max_length=100) phone_number = models.IntegerField() email = models.EmailField() reservation_date = models.DateField() reservation_slot = models.SmallIntegerField(default=10) def __str__(self): return self.name + " " + self.surname This is forms.py: class ReservationForm(ModelForm): class Meta: model = Reservation fields = "__all__" Error message: File "/home/prabhu/Documents/Projects/alcudia-web/my_alcudia/baseweb/views.py", line 50, in bookings email=data['email'], KeyError: 'email' And this is HTML form: <p> <label for="email">Email: </label> <input type="email" placeholder="Your email" maxlength="200" required="" id="email"> </p> Will be glad for any suggestions. -
Cookie is not loading to browser
I have this LoginView in django rest framework. class LoginView(APIView): serializer_class = LoginSerializer authentication_classes = [SessionAuthentication, ] def post(self, request): if request.user.is_authenticated: return Response({'message': 'User is already logged in'}, status=status.HTTP_200_OK) serializer = self.serializer_class(data=request.data) if serializer.is_valid(): email = serializer.validated_data.get('username') password = serializer.validated_data.get('password') user = authentication.authenticate(request, username=email, password=password) if user is not None: login(request, user) response = Response({'message': 'User logged in successfully'}, status=status.HTTP_200_OK) return response else: return Response({'message': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED) else: # If the serializer is not valid, return validation errors return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and this request by axios in vue.js application <script setup> import axios from 'axios' import {ref, onMounted} from 'vue' const email = ref(""); const password = ref(""); axios.defaults.withCredentials = true function login() { axios.post('http://127.0.0.1:8000/api/login/', { username: email.value, password: password.value, })`your text` } </script> when i make request, cookie(session) is load to database, but it is not loaded to browser. Do you have any suggestions why? When i make request from 127.0.0.1:8000/api/login endpoint it works as expected. It doesn't work when i make request from localhost:5173 by axios. -
Use Multi threading in Loop using Python
I have three functions that i want to use async in python in a loop how can I use all 3 functions in a loop using multi-threading I have also mentioned the desired result def sum(a, b): sum= a+b return sum def multi(a, b): mutli= a*b return multi def divide(a, b): divide= a/b return divide final_data = [{'a':1, 'b':3},{'a':7, 'b':5},{'a':6, 'b':4}] for data in final : sum_value = sum(data['a'], data['b'] multi_value = multi(data['a'], data['b'] divide_value = divide(data['a'], data['b'] #desired final output final_data = [{'a':1, 'b':3, 'sum_value':4, 'multi_value':3, 'divide_value':0.34},{'a':7, 'b':5,'sum_value':12, 'multi_value':35, 'divide_value':1.4},{'a':6, 'b':4,'sum_value':10, 'multi_value':24, 'divide_value':1.5}] -
How to create a dynamic menu in Django
The idea is to dynamically create a menu structure with submenus and then expose it in a REST API so frontend can print the menu. Each menu point can have multiple submenu and each submenu can have multiple submenu inside, like: - Menu 1 - Submenu 1.1 - Submenu 1.1.1 - Submenu 1.1.2 - Submenu 1.2 - Submenu 1.2.1 - Submenu 1.2.2 - Menu 2 - [...] What should be the structure of the models and serializers to fulfill the described function? I tried to do it with a single model like: class MenuPoint(models.Model): name = models.CharField(max_length=200) [...] parent_menu_point = models.ForeignKey( 'self', on_delete=models.CASCADE, related_name='submenu_point', blank=True, null=True) Thanks! -
How to get callback code of Django OAuth Toolkit use python?
When open http://localhost/o/authorize/?response_type=code&code_challenge=xxx&code_challenge_method=S256&client_id=xxx&redirect_uri=http://127.0.0.1/callback, will be redirected to http://localhost/admin/login/?next=/o/authorize/%3Fresponse_type%3Dcode%26code_challenge%3Dxxx%26code_challenge_method%3DS256%26client_id%3Dxxx%26redirect_uri%3Dhttp%3A//localhost%3A8000/callback, provide user email and password, and after successfully logging into account, will be redirected to http://localhost/callback?code=xxx. I want get callback code in http://localhost/callback?code=xxx. code: import os import requests from urllib.parse import urlparse, parse_qs url = "http://localhost/admin/" auth_url = 'http://localhost/o/authorize/?response_type=code&code_challenge=xxx&code_challenge_method=S256&client_id=xxx&redirect_uri=http://localhost/callback' email = "email" password = "password" session = requests.Session() session.get(url) login_payload = { 'email': email, 'password': password, 'csrfmiddlewaretoken': session.cookies['csrftoken'] } login_req = session.post(url, data=login_payload) print(login_req) print(login_req.url) auth_page = session.get(auth_url) print(auth_page) print(auth_page.url) output: <Response [200]> http://localhost/admin/login/?next=/admin/ <Response [200]> http://localhost/admin/login/?next=/o/authorize/%3Fresponse_type%3Dcode%26code_challenge%3Dxxx%26code_challenge_method%3DS256%26client_id%3Dxxx%26redirect_uri%3Dhttp%3A//127.0.0.1%3A8000/callback Can't get the callback url, like http://localhost/callback?code=xxx. -
MongoDB - How to reproduce the cursor timeout error due to inactivity?
How do I reproduce CursorNotFound error due to 10 minutes of cursor inactivity using PyMongo tools? def sleep_for_minutes(minutes_to_sleep): for i in range(minutes_to_sleep): print(f'{i} sleeping for 1 minute') time.sleep(60 * 1) # Iterate over all documents in the collection for document in collection.find(): print(f'{document} before sleeping') sleep_for_minutes(15) print(f'{document} after sleeping') Context Am iterating a very large Mongo collection. Each document of a collection is quite large as well. Tech stack : MongoEngine, Django My production system is timing out due to CursorNotFound error. Error goes like this : pymongo.errors.CursorNotFound: cursor id <something> not found, full error: {'ok': 0.0, 'errmsg': 'cursor id <something> not found', 'code': 43, 'codeName': 'CursorNotFound'} As per my understanding, there can 2 possible reasons for the same: Session Idle Timeout which occurs at 30 minutes Cursor inactivity timeout after 10 minutes of inactivity To fix and verify the fixes, I am trying to reproduce there errors on a local setup to fix the issue. I do this by using sleep methods. While I am able to reproduce the 1st situation, I am unable to reproduce the situation when cursor times out after 10 minutes of activity. -
Creating a Docker Image for Python Django Backend and NextJS Frontend with Relative URL Interactions
I'm working on a project that consists of a Python Django backend and a NextJS frontend. I'd like to containerize both components into a single Docker image and have them interact with each other using relative URLs. I've tried building the FE docker image and copying built artefacts into BE image, but I'm running into FE is not running. Could someone guide me on the best practices and steps to achieve this integration? Any insights, example Dockerfiles, or configuration tips would be greatly appreciated. Thank you in advance! -
How to configure python django and blockchain?
I need a project or a guide on how to configure Django and blockchain. -
UnboundLocalError: local variable 'par' referenced before assignment:
I want to get the context data into a par variable to be processed into the pipeline context=par. but got this error, how can i fix this ? def index(request): qas_form = QasForms() post_form = MyForm(request.POST) db_context = Context.objects.filter(category=post_form) for con in db_context : par= con.context context = { 'heading' : 'Question Answering', 'data_form' :qas_form, 'form' : post_form, 'Cont' : db_context, } model_name = BertForQuestionAnswering.from_pretrained('./save_model', from_tf=True) tokenizer = BertTokenizer.from_pretrained('./save_model') nlp = pipeline('question-answering', model=model_name, tokenizer=tokenizer) if request.method == 'POST': question = request.POST['question'] par = hasil result = nlp(question=question, context=par) context['question'] = question context['answer'] = result['answer'] return render(request,'qas/index.html',context) I am trying to get a solution to this problem -
I have accidentally deleted views.py file but I have views.pyc file in pycache is it possible to recover views.py file from views.pyc in python 3.11 [duplicate]
I have tried using online decompiler but it doesn't work. I tried softwares like DiskDrill but that file also not showing in those softwares. -
nginx failing to load ssl certificate
The Problem I used mkcert to make local SSL certificates for a Django project using Docker on Windows but get a "This site can’t provide a secure connection" error when I try to access https://localhost. In the Docker log the output was: 2023-09-26 18:19:47 nginx.1 | 2023/09/27 00:19:47 [error] 38#38: *10 cannot load certificate "data:": PEM_read_bio_X509_AUX() failed (SSL: error:0480006C:PEM routines::no start line:Expecting: TRUSTED CERTIFICATE) while SSL handshaking, client: 172.18.0.1, server: 0.0.0.0:443 What I Tried Followed the directions to set up a new Django project with Docker using the Cookiecutter-Django template. Did everything down through the "Run the Stack" section, and the local development website looked good on localhost. Skipped down to "Developing locally with HTTPS" section and followed those directions. The directions don't specify how to change the files from .pem to .crt or .key, but I just renamed them on the first try. The rest of the template website still works fine, but when I go to https://localhost I get a "This site can’t provide a secure connection" error. I tried changing: -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- to -----BEGIN TRUSTED CERTIFICATE----- ... -----END TRUSTED CERTIFICATE----- in a text editor and still got the same error messages as above. I … -
Can't install mysqlclient on Alpine Linux
I'm trying to run a Django server on a Docker image based on python:3.11-alpine. The app uses a remote MySQL database. When installing the pip dependencies I get this error: 16.70 ERROR: Could not build wheels for mysqlclient, which is required to install pyproject.toml-based projects ------ failed to solve: process "/bin/sh -c pip install -r requirements.txt" did not complete successfully: exit code: 1 These are the installed apk packages: gcc libc-dev linux-headers nodejs mysql mysql-client mysql-dev Is this related to the fact I'm using Alpine Linux? Did I install the wrong drivers. I tried adding the mysql-dev package but the error didn't change. I also saw this GitHub thread, and I fear it's just impossible to use Alpine. -
Find all the ManyToManyField targets that are not connected to a ManyToManyField haver
Suppose I have 2 models connected by a many to many relation from django.db import models class Record(models.Model): name = models.CharField(max_length=64) class Batch(models.Model): records = models.ManyToManyField(Record) Now I want to find all the Records that are not connected to a Batch. I would have thought it would be one of Record.objects.filter(batch=[]) #TypeError: Field 'id' expected a number but got []. Record.objects.filter(batch__count=0) Record.objects.filter(batch__len=0) #FieldError: Related Field got invalid lookup: count Or something like that. But those don't work. They seem to act like they expect batch to be singular rather then a set. What is the correct way to do this?