Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django app runing on Azure Web App + Database PostgreSQL - csrf error
My application is running on Azure, but I get a csrf error on the login page. And yet: My template has the {% csrf_token %} within the element: I have 'django.middleware.csrf.CsrfViewMiddleware', in the MIDDLEWARE definition in settings.py. In addition, you have to know that the same code (besides the migration required by the PostgreSQL usage) is running on another Azure instance with sqlite and is working correctly. As I am a newbie in Azure and web developmeent, any hint is welcome. Best regards -
This happens when i run makemigrations or migrate in django, How do i solve this error?
I'm trying to run makemigrations in my django project, but I get an unsolvable error. My os is fedora 38 and im using vscode this only happens when I'm using postgress database(online). but my code runs fine on sqlite3 database. you can see the error below when I use makemigrations command: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? warnings.warn( No changes detected And when I use migrate command this error happens: Traceback (most recent call last): File "/home/arad/Django/store_project/.venv/lib64/python3.11/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection self.connect() File "/home/arad/Django/store_project/.venv/lib64/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ . . . File "/home/arad/Django/store_project/.venv/lib64/python3.11/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/arad/Django/store_project/stationary_store/manage.py", line 22, in <module> main() File "/home/arad/Django/store_project/stationary_store/manage.py", line 18, in main execute_from_command_line(sys.argv) . . . File "/home/arad/Django/store_project/.venv/lib64/python3.11/site-packages/psycopg2/__init__.py", line 122, in … -
django cannot connect to the database on the server
I have deployed the project and an error occurred Watching for file changes with StatReloader Performing system checks... `System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/django/db/backends/base/base.py", line 289, in ensure_connection self.connect() File "/usr/local/lib/python3.10/dist-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/django/db/backends/base/base.py", line 270, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.10/dist-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/django/db/backends/postgresql/base.py", line 275, in get_new_connection connection = self.Database.connect(**conn_params) File "/usr/local/lib/python3.10/dist-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: fe_sendauth: no password supplied The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.10/dist-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/django/core/management/commands/runserver.py", line 136, in inner_run self.check_migrations() File "/usr/local/lib/python3.10/dist-packages/django/core/management/base.py", line 574, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/usr/local/lib/python3.10/dist-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python3.10/dist-packages/django/db/migrations/loader.py", line 58, in __init__ self.build_graph() File "/usr/local/lib/python3.10/dist-packages/django/db/migrations/loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/local/lib/python3.10/dist-packages/django/db/migrations/recorder.py", line 81, in applied_migrations if self.has_table(): File "/usr/local/lib/python3.10/dist-packages/django/db/migrations/recorder.py", line 57, in has_table with self.connection.cursor() as cursor: File "/usr/local/lib/python3.10/dist-packages/django/utils/asyncio.py", … -
Django and Mongo db
BooleanField gives back Database Error and no exception message supplied. I tried using 'integer value with 0 and 1, char value with yes and no and researched every issues but still no answers or solutions. In my Website i can't seem to change the is_sold to yes or no as a client which is probably due to the mongo db issues or limitation or its nature. here is the error image ] from django.contrib.auth.models import User from django.db import models from djongo import models class Category(models.Model): name = models.CharField(max_length=255) class Meta: ordering = ('name',) verbose_name_plural = 'Categories' def __str__(self): return str(self.name) class Item(models.Model): category = models.ForeignKey(Category, related_name='items', on_delete=models.CASCADE) name = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) price = models.FloatField() image = models.ImageField(upload_to='item_images', blank=True, null=True) # is_sold = models.BooleanField(default=False) published_by = models.ForeignKey(User, related_name='items', on_delete=models.CASCADE) published_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.name) -
Images not getting displayed on Apache server
Error Screenshot I built a website using the Django framework and hosted it on an Apache server. The images are not getting displayed for some reason. It is giving me a 404 error (please see the attached image) but I am sure it is looking at the right place. However, it is fetching other sorts of files like csv but not images. Also, when I run it on a local server, the images are getting displayed. Can someone please help me out? I tried to change the way I am specifying the path but it is still not working (please see the attached images).Code Part-1 Code Part-2 Code Part-3 -
How to get APPEND_SLASH to work properly with nginx rewrite?
I have this in nginx config location /todjango/ { rewrite ^/todjango(/.*)$ $1 break; uwsgi_pass django; In urls.py urlpatterns = [ path("foo/", include("foo.urls")) ] APPEND_SLASH is True by default When I type curl http://localhost:8000/todjango/foo I want to get 301 to /todjango/foo/, but instead I get 301 to /foo/. When APPEND_SLASH is False I get 404 as expected -
How can I change this model for multiple choice answer?
I am making a Django app for multiple choice question-answer exam. I have created a Question model as below. class Question(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) question_name = models.CharField(max_length=200,null=True) option1 = models.CharField(max_length=200,null=True) option2 = models.CharField(max_length=200,null=True) option3 = models.CharField(max_length=200,null=True) option4 = models.CharField(max_length=200,null=True) answer = models.CharField(max_length=200,null=True) def __str__(self): return self.question_name It is working fine, but now I want to change it so that question can have more that one option as correct answer. How can I achieve it? I will be adding the questions for my app from admin panel. I want to add quesion , their options and then mark the right answer/answers (it is possible to) otherwise make a field that can hold the right answer/answers Is there any way to make a field both CharField and BooleanField ? Or what approach should I take to complete my goal ? Thanks in advance for the suggestions!! :) -
How can I inline a Form of a OneToOne Relation
I have the following django models where a OneToOne Relation is used. Models: class ClientCustomFields(models.Model): some_custom_id = models.CharField(max_length=36, blank=True, null=True) # .... more custom fields class Client(ExternalIdModel): first_name = CharField(max_length=200) last_name = CharField(max_length=200) Now, since this is an easy 1:1 relation, I want to embed the form of the custom fields directly into the form of the customer. But I am having troubles stitching the Forms together. class ClientCustomFieldsForm(ModelForm): class Meta: model = ClientCustomFields fields = '__all__' class ClientForm(ModelForm): custom_fields = ClientCustomFieldsForm() class Meta: model = Client fields = '__all__' I have tried a couple of others like BaseInlineFormSet but without any luck so far. Although there is a similar question here on SO, this however, is admin related and at least I could not figure out how this could help me. -
is there a way for optimize this piece of code?
I have these two model below: models.py file: class Profile(models.Model): """ User Profile Model This model represents a user's profile information, including their avatar, location, city, address, and geographical coordinates (latitude and longitude). Fields: - user (OneToOneField): The associated user instance. - avatar (ImageField): An optional user avatar (profile picture). - location_picture (ImageField): An optional picture of the user's location. - city (CharField): An optional field for the user's city. - address (CharField): An optional field for the user's address. - latitude (DecimalField): An optional field for the latitude of the user's location. Valid range: -90.0 to 90.0. - longitude (DecimalField): An optional field for the longitude of the user's location. Valid range: -180.0 to 180.0. """ user = models.OneToOneField( settings.AUTH_USER_MODEL, verbose_name=_("User"), help_text=_("the profile of a user instance."), db_comment=_("the profile of a user instance."), on_delete=models.CASCADE ) city = models.CharField( verbose_name=_("City"), help_text=_("'Optional'.this is the city of the user."), db_comment=_("'Optional'.this is the city of the user."), max_length=255, null=True, blank=True ) address = models.CharField( verbose_name=_("Address"), help_text=_("'Optional'.this is the address of a user."), db_comment=_("'Optional'.this is the address of a user."), max_length=255, null=True, blank=True ) shair_location = models.BooleanField( verbose_name=_("Shair Location"), default=False, help_text=_("'Optional.thie mean you want to shair your location or not!'"), db_comment=_("'Optional.this mean you want … -
How to pass dictionary data to chart.js in django?
I want to get a report by chart from my model but I can't figured out how to pass data from a dictionary to chart using chart.js? here is my model: class Book(models.Model): number = models.CharField(_("number"), max_length=255) title = models.CharField(_("title"), max_length=255) subtitle = models.CharField(_("subtitle"), max_length=255, null=True,) authors = models.TextField(_("authors"), null=True,) publisher = models.CharField(_("publisher"), max_length=255, null=True,) published_date = models.DateField(_("published date"), null=True,) category = models.CharField(_("category"), max_length=255, null=True,) distrubution_expense = models.FloatField(_("distribution expense")) def __str__(self): return self.title def get_absolute_url(self): return reverse('book_detail', args=[str(self.id)]) and this is my view that I use queryset to count the number of categories repetition: class CategoryChartListView(generic.ListView): model = Book template_name= 'pages/chart_category.html' def get_context_data(self, **kwargs): context = super(CategoryChartListView, self).get_context_data(**kwargs) context["dictCategory"] = Book.objects.values('category').annotate(count=Count('category')) return context also this is the dictionary that I get from above queryset in view: {'category': 'Business Analytics', 'count': 336} {'category': 'Data ethics', 'count': 389} {'category': 'visualization', 'count': 314} {'category': 'statistics', 'count': 428} {'category': 'NLP', 'count': 368} {'category': 'Language', 'count': 1} {'category': 'python', 'count': 373} {'category': 'maths', 'count': 379} {'category': 'deep learning', 'count': 364} {'category': 'SQL', 'count': 403} {'category': 'Python', 'count': 80} {'category': 'R Studio', 'count': 246} {'category': 'data science', 'count': 395} {'category': None, 'count': 0} and template: {%block content%} <!-- displaying the chart --> <!-- you can also … -
Django Queryset: iterate through nested array of objects in JSONField using annotation and F expressions
In my Django 4.2 project, I have a model with some JSONField (using PgSQL and the DB backend), e.g. from django.db import models class MyModel(models.Model): my_json = models.JSONField(null=True, blank=True) ... And model instances contain nested arrays of JSON objects, e.g. { "members":[ { "name": "Person #1", "age": 41 }, { "name": "Person #2", "age": 51 } ], "other_data": ... } While obtaining MyModel instances from the DB, I'd like to simplify the content to be returned later in the View, so that I don't return complete array of members objects (for each model instance) but only an array of string (their names). I.e. instead of returning content like: [ { "members":[ { "name": "Person #1.1", "age": 41 }, { "name": "Person #1.2", "age": 51 } ], "other_data": ... }, { "members":[ { "name": "Person #2.1", "age": 42 }, { "name": "Person #2.2", "age": 52 } ], "other_data": ... }, ... ] I'd actually like to return: [ { "member_names":["Person #1.1", "Person #1.2"], "other_data": ... }, { "member_names":["Person #2.1", "Person #2.2"], "other_data": ... }, ... ] I'd like to use Django queryset annotation to introduce member_names property above, which would summarize the name properties from related members array (of each model … -
Referencing a non primary foreign key in Django ORM
How can I select entries in one table based on criteria in another table in Django's ORM if the foreign key is not referencing a primary key but another column with unique constraint? The corresponding SQL command would be: SELECT TableMoon.name FROM TableMoon JOIN TablePlanet ON TableMoon.planet = TablePlanet.name WHERE classification = 'inner_planet'; The expected answer would be: Moon, Phobos, Deimos Background I have a Django app that is connected to a legacy sqlite database. I am not allowed to modify the database scheme. The database looks like this: TablePlanet ------------------------------------ planet_id | name | classification ------------------------------------ 1 | Mercury | inner_planet 2 | Venus | inner_planet 3 | Earth | inner_planet 4 | Mars | inner_planet 5 | Jupiter | outer_planet 6 | Saturn | outer_planet 7 | Uranus | outer_planet 8 | Neptune | outer_planet TableMoon ------------------------ moon_id | planet | name ------------------------ 1 | Earth | Moon 2 | Mars | Phobos 3 | Mars | Deimos 4 | Jupiter | Io 5 | Jupiter | Europa 6 | Jupiter | Ganymede The column TablePlanet.name has a unique constraint. The column TableMoon.planet has a foreign key constraint that references TablePlanet.name. This is the SQL code for the … -
Django window function to partition over a subquery
So, given I have a table in django: class A(models.Model): a: models.CharField(max_length=10) I want to replicate this SQL using django's ORM: SELECT "id" FROM ( SELECT id, a FROM a_a LIMIT 100000 ) inner ORDER BY RANK() OVER (PARTITION BY a); The window function part I get, but I'm unable to figure out how to partition over a subquery in django, which I need for applying the limit. -
Django: Relationship between 3 models
I'm working on an app for construction company, and I want to create our daily schedule. For this matter, I have 3 models Date, Construction_site and Machinery. Each day we are working on several construction sites and we have 3-4 machines/vehicles per CS. I want to get something like this, but I'm stuck with the relationships between models. 2023-09-21 Construction site 1 Excavator 1 Excavator 2 Truck 1 Construction site 2 Excavator 3 Excavator 4 Truck 2 Construction site 3 Buldozer Truck 3 2023-09-22 Construction site 1 Excavator 1 Excavator 2 Truck 1 Construction site 2 Excavator 3 Truck 2 Construction site 3 Buldozer Excavator 4 Truck 3 Simplified models: class Date(models.Model): date = models.DateField() class Construction_site(models.Model): construction_site_name = models.CharField(max_length=50) date = models.ManyToManyField(Date) class Machinery(models.Model): machine_name = models.CharField(max_length=50) construction_site_name = models.ManyToManyField(Construction_site) Once my models are correct I need to create a view that will show all construction sites and used machinery for the specific date. def date(request): date = Date.objects.get(id=1) construction_sites = date.construction_site_set.all() This will return all construction sites for the specific date, but I'm unable to get used machinery. I'm fairly new to Django, so any help is welcome. -
sprate three digit with cama in django shopping project
i have a html file that get my product model from database and show price of products. i have a view: def product(request): all_products = Product.objects.all() return render(request, 'index.html', {'products':all_products}) and in html file i write: {% for item in products %} {{ item.price }} {% endfor %} i want for price for example: 1000000 $ output in html file show like this: 1,000,000 $ is there anyway to do this? i'm not familiar with java script... so please help! -
My Django form is not getting submitted, despite getting 200 status in terminal
I am working on a personal project of mine to upload SD models and download them. When I adding the model through admin its working fine and getting displayed in the model_list view , but when I add it using the form I have created its not adding the model into the db, and also not redirecting to the url. I think the problem could be that I have not added the creator field in the form. I have created the model as shown below: from django.db import models from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ from django.core.validators import FileExtensionValidator from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass # Create your models here. class MLModel(models.Model): name = models.CharField(max_length=255, help_text="Name of the model") description = models.TextField(blank=True, null=True, help_text="Description of the model") upload_date = models.DateTimeField(auto_now_add=True, help_text="Date and time of upload") type = models.ForeignKey("Type", on_delete=models.CASCADE, help_text="Type of model") category = models.ForeignKey("Category", on_delete=models.CASCADE, help_text="Category of the model") sd_base_model = models.ForeignKey("SDBaseModel", on_delete=models.CASCADE, help_text="Stable Diffusion version for the model") trigger_words = models.CharField(max_length=50, help_text="trigger words for easy search of the model") epochs = models.IntegerField(help_text="epochs of the model trained") steps = models.IntegerField(help_text="steps of the model trained") model_file = models.FileField(upload_to='static/models', validators=[FileExtensionValidator(allowed_extensions=['ckpt', 'pt', 'safetensors', 'bin', 'zip', 'yaml', 'yml'])], … -
Stream video from s3 bucket to web player
Python + Django + Video.js. As pet-project I want to do my own cloud web – gallery. I made S3 – compatible object storage and uploaded video file in it. I want to stream this video on my web-site, like YouTube, without downloading full video. I know, that I can create a pre-signed URL, but I think it isn’t the best idea, because I would have many video files. I found «_raw_stream» method, as I understand, in response I get bytes. How I can use this method to transmit video in web-player? Or maybe you please tell me another way, how to stream video from s3 bucket to web player? THX! -
Duplicate push notification at a time send via firebase
I face a weird problem, with push notifications using Firebase and Django fcm-device. When a file upload is done, then push notification to desired users. I ensure that this function calls only one time after the video upload is completed. Suddenly 20-30 notifications are sent for one single upload to desired users. This issue stays approx 5-10h. But now it's fine again, no problems. Then what would be the reason for this behavior? -
I want to create a like counter in Django, but I get an error
I want to create a like counter for an exercise project that receives and counts the number of likes from self and displays them in templates . from django.db import models from django.contrib.auth.models import User from django.urls import reverse class post(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, related_name='posts') title = models.CharField(max_length=150) body = models.TextField() slug = models.SlugField() create = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.title} - {self.update}' # Define a get_absolute_url() method to tell Django # how to calculate the canonical URL for an object. def get_absolute_url(self): return reverse('home:post_detail',args=(self.pk ,self.slug)) def likes_count(self): ....... #My problem is here class Vote(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,name='uvote') post = models.ForeignKey(post,on_delete=models.CASCADE , name='pvote') def __str__(self) -> str: return f'{self.uvote} ---- {self.pvote.slug}' I tried this code (told to me in my tutorial) def likes_count(self): return self.pvote.count() -
Get download count via download attribute with Django
I'm doing a project with Django, like a music player, this is my models: class Song(models.Model): """Model representing a song""" name = models.CharField( max_length=200, help_text=_('Enter a song name')) image = models.ImageField( upload_to='cover_image') content = models.FileField(upload_to='songs') artist = models.ForeignKey(User, on_delete=models.CASCADE) status = models.BooleanField( default=False, help_text=_('Check this box to make the song public') ) since I already configured the uploaded folder and all, all I have to do in my templates is adding the download attribute to the tag and it will download file for the user <a href="/media/{{ i.content }}" download="{{ i.name }}" type="video/mp4"> <button class="btn btn-outline-danger">Download Song </button> </a> This works flawlessly, however it proves to be quite difficult if I want to get the download count for the song. I'm thinking of giving it the tag an onclick attribute so when I click the download button it will trigger a javascript function to send a hidden form to views to increment the downloads value. However this I think is quite convoluted so I wonder if there is a better way to do this. -
How to Connect Azure Mysql Database with Django Project
I am Trying to Connect my Django Project with the Azure Mysql Database but it's show this error continuously: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': (2003, "Can't connect to MySQL server on 'dummyserver.database.windows.net' (timed out)") and this is easily able to connect with the Azure Data Studio, don't know why it's not working in this Django Project, may you please help me out in any way so that i can be able to make this done, even i am able to make the connection to the local Mysql Server and able to migrate the Table and Models, but when i am trying to do this with Azure Mysql Database, then not and it's sure that all the details i put in the configuration. i had also followed these links: https://learn.microsoft.com/en-us/samples/azure-samples/azure-sql-db-django/azure-sql-db-django/ Hope for Help, ASAP i just want to make this Connection Done and able to migrate all my models to the Azure Mysql Database, with the help of my Django project -
How to use raw query in django tastypie and join tables?
I am trying to use a raw query in django tastypie queryset. But django is throwing me the following exception: <error_message>'RawQuerySet' object has no attribute 'filter'</error_message> I also tried using ModelName.objects.filter() to join different tables. It's not working either. Django throwing the following exception: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. My tastypie models.py file looks like this: import datetime from django.db import models from tastypie.resources import ModelResource from logsheet.models import * from generation.models import * from django.contrib.auth.models import User from tastypie.authentication import BasicAuthentication from django.db.models import Sum class EnergyPlantWiseResource(ModelResource): class Meta: present_time = datetime.datetime.today() previous_month = present_time.month - 1 present_year = present_time.year queryset = EnergyPlantWise.objects.raw('SELECT 1 id, SUM(ep.kwh), f.name FROM energy_plant_wise ep, fuel f WHERE ep.fuel_id=f.id AND MONTH(ep.date)=%s AND YEAR(ep.date)=%s GROUP BY f.name',[previous_month, present_year]) # queryset = EnergyPlantWise.objects.all() resource_name = 'epw' allowed_methods = ['get'] excludes = ['id'] -
Receiving Keywords from Spring Boot to Django
I'm working on sending a keyword from Spring Boot to Django. @RestController public class ProfileController { private final RestTemplate restTemplate; public ProfileController(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @GetMapping("/sendprompt") public ResponseEntity<String> sendprompt(@RequestParam String keyword) { try { System.out.println("keyword: " + keyword); String djurl = "http://localhost:8000/makingimage"; Map<String, String> map = new HashMap<>(); map.put("keyword", keyword); restTemplate.getForEntity(djurl, String.class); return ResponseEntity.ok("success"); } catch (Exception e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred."); } } } ProfileController.java Since I haven't implemented the frontend yet, I'm manually entering the keyword in the URL like this:http://localhost:8080/sendprompt?keyword=castle class MakingImage(APIView): def t2i(self, prompt, negative_prompt): try: r = requests.post( 'https://api.kakaobrain.com/v2/inference/karlo/t2i', json={ 'prompt': prompt, 'negative_prompt': negative_prompt }, headers={ 'Authorization': f'KakaoAK {REST_API_KEY}', 'Content-Type': 'application/json' } ) response = json.loads(r.content) return response.get("images")[0].get("image") except Exception as e: print(f"An error occurred in t2i: {e}") return None image_url = None def making_image(self, request): response = None if request.method == "GET": print("get") prompt = request.GET.get("keyword") negative_prompt = "sleeping cat, dog, human, ugly face, cropped" response = self.t2i(prompt, negative_prompt) else: print("post") return Response(response, status=status.HTTP_200_OK) models.py When a keyword is sent from Spring Boot to the address at 8080, Django receives the keyword and utilizes the t2i function to generate an image within the making_image function. from django.urls import path from .views … -
Django exclude() query with violation
I have this model: class SettingMenus(models.Model): cat = models.ForeignKey(Setting, on_delete=models.CASCADE, related_name="menus", null=True) index = models.SmallIntegerField(validators=[MaxValueValidator(32766)], default=0) name = models.CharField(max_length=100, null=True) path = models.CharField(max_length=200, null=True, blank=True) parent = models.ForeignKey('self', null=True, blank=True, related_name='sub_categories', on_delete=models.CASCADE) role = models.ManyToManyField(UserRole, related_name="settingMenus", blank=True) tables = models.ManyToManyField(AppModels, related_name="setting_menus", blank = True,) And a query in view: nv1menus = SettingMenus.objects.filter( cat__company__name=company, cat__application="common", index=0, role__in=request.user.groups.all() ).exclude(sub_categories__role__in=request.user.groups.all()).distinct() How I can violating sub_categories__role__in=request.user.groups.all() which is in exclude? I have tried: sub_categories__role__in!=request.user.groups.all() or not sub_categories__role__in=request.user.groups.all() But not works. -
Merging multiple querysets using union is showing error with Count in annotate
I have a simple django app and I am trying to merge multiple querysets using union but one of my queryset contains annotate with Count. I mean it is showing each UNION query must have the same number of columns LINE 1: ...::date GROUP BY 1 ORDER BY 15 DESC) UNION (SELECT I am using Count in annotate most liked blog post and most viewed blog post like filter_blog_posts = Blog.objects.annotate(f=Count("likes") + Count("views")) and other query which I am merging with is new_blogs = Blog.objects.order_by("-date") and like merged_q = Blog.objects.none() merged_q = merged_q.union(filter_blog_posts) merged_q = merged_q.union(new_blogs) and When I remove annotate then it is working fine but not with it. I saw many topics on showing error with annotate with union like this. and I also tried with it by adding values but my other queries will also need to be changed but I don't want to limit the fields. Any help would be much appreciated.