Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why form.is_valid() is always false?
I tried to create a contact us form in django but i got always false when i want to use .is_valid() function. this is my form: from django import forms from django.core import validators class ContactForm(forms.Form): first_name = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'نام خود را وارد کنید'}), label="نام ", validators=[ validators.MaxLengthValidator(100, "نام شما نمیتواند بیش از 100 کاراکتر باشد")]) last_name = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'نام خانوادگی خود را وارد کنید'}), label="نام خانوادگی", validators=[ validators.MaxLengthValidator(100, "نام خانوادگی شما نمیتواند بیش از 100 کاراکتر باشد")]) email = forms.EmailField( widget=forms.EmailInput( attrs={'placeholder': 'ایمیل خود را وارد کنید'}), label="ایمیل", validators=[ validators.MaxLengthValidator(200, "تعداد کاراکترهایایمیل شما نمیتواند بیش از ۲۰۰ کاراکتر باشد.") ]) title = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'عنوان پیام خود را وارد کنید'}), label="عنوان", validators=[ validators.MaxLengthValidator(250, "تعداد کاراکترهای شما نمیتواند بیش از 250 کاراکتر باشد.") ]) text = forms.CharField( widget=forms.Textarea( attrs={'placeholder': 'متن پیام خود را وارد کنید'}), label="متن پیام", ) def __init__(self, *args, **kwargs): super(ContactForm, self).__init__() for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form_field require' this is my view: from django.shortcuts import render from .forms import ContactForm from .models import ContactUs def contact_us(request): contact_form = ContactForm(request.POST or None) if contact_form.is_valid(): first_name = contact_form.cleaned_data.get('first_name') last_name = contact_form.cleaned_data.get('last_name') email = contact_form.cleaned_data.get('email') title = contact_form.cleaned_data.get('title') text = contact_form.cleaned_data.get('text') ContactUs.objects.create(first_name=first_name, last_name=last_name, email=email, … -
how to call a property from values in django
I need the value of the property, which calls through the values call so that later i will use in the union method so used model is class Bills(models.Model): salesPerson = models.ForeignKey(User, on_delete = models.SET_NULL, null=True) purchasedPerson = models.ForeignKey(Members, on_delete = models.PROTECT, null=True) cash = models.BooleanField(default=True) totalAmount = models.IntegerField() advance = models.IntegerField(null=True, blank=True) remarks = models.CharField(max_length = 200, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) class Meta: ordering = ['-update', '-created'] def __str__(self): return str(self.purchasedPerson) @property def balance(self): return 0 if self.cash == True else self.totalAmount - self.advance when i call the model as bills = Bills.objects.all() I can call the balance property as for bill in bills: bill.balance no issue in above method but i need to use the bills in union with another model so needed fixed vales to call i am calling the method as bill_trans = Bills.objects.filter(purchasedPerson__id__contains = pk, cash = False).values('purchasedPerson', 'purchasedPerson__name', 'cash', 'totalAmount', 'id', 'created') in place of the 'totalamount' i need balance how can i approach this step -
Django cannot save a CharField with choices
I have this CharField with some choices: M = 'Male' F = 'Female' O = 'Other' GENDER = [ (M, "Male"), (F, "Female"), (O, "Other") ] gender = models.CharField(max_length=10, choices=GENDER) When I try and save a model in the database I get the following error: django.db.utils.DataError: malformed array literal: "" LINE 1: ...ddleq', 'Cani', '1971-09-01'::date, '{Male}', '', ''::varcha... ^ DETAIL: Array value must start with "{" or dimension information. The {Male} value is so because I made the front end send the value like that but it's not that and the error makes no sense. Please can someone tell me why am I getting this error and how to fix it pls? I use the Python 3.8 Django 4.1 PostGreSQL -
nginx unable to load media files - 404 (Not found)
I have tried everything to serve my media file but yet getting same 404 error. Please guide. My docker-compose file: version: "3.9" services: nginx: container_name: realestate_preprod_nginx_con build: ./nginx volumes: - static_volume:/home/inara/RealEstatePreProd/static - media_volume:/home/inara/RealEstatePreProd/media networks: glory1network: ipv4_address: 10.1.1.8 expose: - 8000 depends_on: - realestate_frontend - realestate_backend real_estate_master_db: image: postgres:latest container_name: realestate_master_db_con env_file: - "./database/master_env" restart: "always" networks: glory1network: ipv4_address: 10.1.1.5 expose: - 5432 volumes: - real_estate_master_db_volume:/var/lib/postgresql/data real_estate_tenant1_db: image: postgres:latest container_name: realestate_tenant1_db_con env_file: - "./database/tenant1_env" restart: "always" networks: glory1network: ipv4_address: 10.1.1.9 expose: - 5432 volumes: - real_estate_tenant1_db_volume:/var/lib/postgresql/data realestate_frontend: image: realestate_web_frontend_service container_name: realestate_frontend_con restart: "always" build: ./frontend command: bash -c "./realestate_frontend_ctl.sh" expose: - 8092 networks: glory1network: ipv4_address: 10.1.1.6 depends_on: - real_estate_master_db - real_estate_tenant1_db realestate_backend: image: realestate_web_backend_service container_name: realestate_backend_con restart: "always" build: ./backend command: bash -c "./realestate_backend_ctl.sh" expose: - 8091 volumes: - static_volume:/home/inara/RealEstatePreProd/static - media_volume:/home/inara/RealEstatePreProd/media networks: glory1network: ipv4_address: 10.1.1.7 env_file: - "./database/env" depends_on: - realestate_frontend - real_estate_master_db - real_estate_tenant1_db networks: glory1network: external: true volumes: real_estate_master_db_volume: real_estate_tenant1_db_volume: static_volume: media_volume: My nginx configuration file: upstream realestate_frontend_site { server realestate_frontend:8092; } server { listen 8000; access_log /home/inara/RealEstatePreProd/realestate_frontend-access.log; error_log /home/inara/RealEstatePreProd/realestate_frontend-error.log; client_max_body_size 0; location / { proxy_pass http://realestate_frontend_site; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; client_max_body_size 0; } } upstream realestate_backend_site { server realestate_backend:8091; } server { listen … -
How to use Django signals when has role based decorators?
I 'm trying to add signals when an employer or admin/staff has created a shift. Currently I have a view like this, I 'm wondering how should I modify it so I can have a post-save signal? @login_required @admin_staff_employer_required def createShift(request): user=request.user employer=Employer.objects.all() form = CreateShiftForm() if request.method == 'POST': form = CreateShiftForm(request.POST) if form.is_valid(): form.save() messages.success(request, "The shift has been created") return redirect('/shifts') else: messages.error(request,"Please correct your input field and try again") context = {'form':form} return render(request, 'create_shift.html', context) Thanks for your help! -
"Quickstart: Compose and Django" documentation explanation. What does version refer to?
Hi I'm doing this documentation for docker. and I have to add this code to docker-compose file(step 9) version: '3' services: db: image: postgres web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db My question is, this is docker-compose version or docker? My instructor said it must be your docker version but 2.13.0 is the latest docker-compose version and Version 20.10.21 is latest docker version. My docker version is 20.10.17 and my docker-compose version is v2.6.1 what is 3? python version?! -
if number inputted is between 0 - 20000 update products prices [closed]
my company needs dev work and although I am not a dev I can read and write code a bit and have created an awesome capture form to load clients into our database. However I am currently stuck on a requirement. (Some Back ground) I built a django app which has some js functions in the html. We have products which I have made a dropdown in the form with set prices depending on the product selected it will update the field with the prices. ` if (Product.value == "certain cover"){ $('#Do_Premium').val('49'); $('#Premium').val('49');} ` Now there is a requirement to add tiering , say you are a silver member the prices will be lower (silver instead of 49 you will get "39") (Gold instead of 39 you will get "29") and so on. Now the QUESTION when the form loads a client is to put a number in that needs to be linked to a tier ie. 0-20000 Silver 20001 - 400000 Gold and so on . How would I code it so that when the user puts the number in it does a check to see which tier it needs to go use and then update field with that … -
Django xhtml2pdf error - SuspiciousFileOperation
I am implementing xhtml2pdf module for my django app. I have been able to print reports, however I am not getting my static configuration to work. I am getting error SuspiciousFileOperation at /moc-content/165/print-report The joined path (/moc/static/moc/main.css) is located outside of the base path component (/Users/xxx/Documents/django-projects/MOC/env/lib/python3.10/site-packages/django/contrib/admin/static) I have implemented link_callback function as xhtml doc is suggesting, but could not figure it out whats wrong with my settings: # settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'moc/static') STATIC_URL = 'moc/static/' # Media files (uploads) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = 'moc/media/' My xhtml functions are as per official docs My vs code directory tree https://i.stack.imgur.com/FWGuv.png -
Django Template: How to check if a variable is in another variable?
Beginner in Django here , I want to check if a particular string variable is in another variable inside the for loop. a = 'abc' b = 'abcd' I have tried below codes:- {% if a in b %} {% if '{{a}}' in b %} {% if '{{a}}' in '{{b}}' %} But none of them seem to work , can anybody guide me here please ? -
Django Raw SQL not returning expected results
I have the below function - it takes orgid, journalid and pid as url parameters. It SHOULD apply those filters to the journal.objects before running the query. However, it returns everything, even when there is only one record meeting the criteria passed in the URL params, Is there anything obvious that would cause that to happen? Thanks a lot @login_required(login_url='/login/') def viewjournal(request, orgid, journalid, pid): user = request.user journals = journal.objects.filter(orgid=org.objects.get(orgid=orgid), updateid=journalid, projectid=project.objects.get(projectid=pid)).raw(''' SELECT 1 as id, updateid, app_journal.orgid, app_journal.projectid, actions, datetime, epoch, app_project.projeectname FROM app_journal left join app_project on app_project.projectid = app_journal.projectid and app_project.orgid = app_journal.orgid''') return render(request, 'pmjournal.html', {'journals': journals}) -
How to attach foreign key associated with the multiple models to submit one form
How can in create inline formset which share the same foreign key using function base views. I don't want to keep selecting product title(which is the FK to other forms) because am using two forms with linked to one Foreign key# i want to implement this https://www.letscodemore.com/blog/django-inline-formset-factory-with-examples/ in function base views I have these 3 models #product model class Product(models.Model): title = models.CharField(max_length=150) short_description = models.TextField(max_length=100) def __str__(self): return self.title *Image model* class Image(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) image = models.ImageField(blank=True, upload_to='images') def __str__(self): return self.product.title *variant model* class Variant(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE) size = models.CharField(max_length=100) quantity = models.PositiveIntegerField(default=1) price = models.DecimalField(max_digits=12, decimal_places=2) def __str__(self): return self.product.title Forms **Forms** from django import forms from django.forms import inlineformset_factory from .models import ( Product, Image, Variant) class ProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' widgets = { 'title': forms.TextInput( attrs={ 'class': 'form-control'} ), 'short_description': forms.TextInput( attrs={'class': 'form-control'}), } class ImageForm(forms.ModelForm): class Meta: model = Image fields = '__all__' class VariantForm(forms.ModelForm): class Meta: model = Variant fields = '__all__' widgets = { 'size': forms.TextInput(attrs={'class': 'form-control'} ), 'quantity': forms.NumberInput(attrs={'class': 'form-control'}), 'price': forms.NumberInput(attrs={ 'class': 'form-control'}), } VariantFormSet = inlineformset_factory( Product, Variant, form=VariantForm, extra=1, can_delete=True, can_delete_extra=True ) ImageFormSet = inlineformset_factory( Product, … -
Django ImportError: cannot import name 'Post' from partially initialized module (most likely due to a circular import)
So I have an app tentacle that has a processor.py file which imports some Models. The models.py also imports that function as it is used on a model's save method. Now when migrating I get a circular import error. I already tried these and changed the import from relative to an absolute alike version which didnt help. So how to "mutually" share the models and function inside processor.py and models.py which are located in sibling apps? -
Django Rest Framework Cannot save a model it tells me the date must be a str
I have this Profile model that also has location attached to it but not trying to save the location now only trying to save the Profile but get an error: class Profile(models.Model): # Gender M = 'M' F = 'F' O = 'O' GENDER = [ (M, "male"), (F, "female"), (O, "Other") ] # Basic information background = models.FileField(upload_to=background_to, null=True, blank=True) photo = models.FileField(upload_to=image_to, null=True, blank=True) slug = AutoSlugField(populate_from=['first_name', 'last_name', 'gender']) first_name = models.CharField(max_length=100) middle_name = models.CharField(max_length=100, null=True, blank=True) last_name = models.CharField(max_length=100) birthdate = models.DateField() gender = models.CharField(max_length=1, choices=GENDER, default=None) bio = models.TextField(max_length=5000, null=True, blank=True) languages = ArrayField(models.CharField(max_length=30, null=True, blank=True), null=True, blank=True) # Location information website = models.URLField(max_length=256, null=True, blank=True) # owner information user = models.OneToOneField(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "profile" verbose_name_plural = "profiles" db_table = "user_profiles" def __str__(self): return self.first_name + ' ' + self.last_name def get_absolute_url(self): return self.slug and this is the view I am using to save the Profile with. I tried sending the data to a serializer first and saving that but the serializer was invalid every time: class CreateProfileView(APIView): permission_classes = [permissions.IsAuthenticated] def post(self, request): data = dict(request.data) location = {} location.update(street=data.pop('street')) location.update(additional=data.pop('additional')) location.update(country=data.pop('country')) … -
Django call function to save file cannot work
I am create Django project and create function for download file, But my project cannot work view.py from django.http.response import HttpResponse from django.conf import settings from django.http import HttpResponse, Http404 def index(request): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filename = 'my_file.json' filepath = BASE_DIR + '/filedownload/' + filename download(request,filepath) return HttpResponse('Download File') def download(request, path): file_path = path if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/x-download") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 How can I solve this? -
Get the first three human readable elements in a queryset
I'm trying to render elements in a Django view. Every clinic object has many specialities, but for estetic reasons I only want the first three of them to be displayed in the template. I've tried: def clinics_index(request): clinics = Clinic.objects.all() for clinic in clinics: speciality = clinic.get_speciality_display context = { 'clinics' : clinics, 'speciality' : speciality.first, } return render(request, 'guide/clinic/clinic_directory.html', context) This now renders the human-readable name of the speciality field (which is a multiple choice field in the model). However, I can't use substraction to only get 3 elements like here: speciality = clinic.get_speciality_display[:3] As I get the following error: TypeError at /guide/clinics/ 'method' object is not subscriptable How can I render it? -
No module named 'graphql.type' in Django
I am New in Django and GraphQL, following the the article, I am using python 3.8 in virtual env and 3.10 in windows, but same error occurs on both side, also tried the this Question, i also heard that GraphQL generate queries, But dont know how to generate it, But this error occurs: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/talha/ve/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/talha/ve/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/home/talha/ve/lib/python3.8/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/talha/ve/lib/python3.8/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/home/talha/ve/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/talha/ve/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/talha/ve/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/talha/ve/lib/python3.8/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed … -
How to Change the Format of a DateTimeField Object when it is Displayed in HTML through Ajax?
models.py class Log(models.Model): source = models.CharField(max_length=1000, default='') date = models.DateTimeField(default=datetime.now, blank = True) views.py The objects in the Log model are filtered so that only those with source names that match a specific account name are considered. The values of these valid objects will then be listed and returned using a JsonResponse. def backlog_list(request): account_name = request.POST['account_name'] access_log = Log.objects.filter(source=account_name) return JsonResponse({"access_log":list(access_log.values())}) dashboard.html This Ajax script is the one that brings back the account name to the views.py. If there are no valid objects, the HTML will be empty; however, it will display it like this otherwise. <h3>You scanned the QR code during these times.</h3> <div id="display"> </div> <script> $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'POST', url : "/backlog_list", data:{ account_name:$('#account_name').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success: function(response){ console.log(response); $("#display").empty(); for (var key in response.access_log) { var temp="<div class='container darker'><span class='time-left'>"+response.access_log[key].date+"</span></div>"; $("#display").append(temp); } }, error: function(response){ alert('An error occurred') } }); },1000); }) </script> My goal is to have the Date and time displayed like "Jan. 10, 2000, 9:30:20 A.M." I've tried changing the format directly from the models.py by adding "strftime" but the error response is triggered. -
Adding a custom, non-model attribute to query set in Django?
Newbie to DRF and have a model called posts. And another called user. The post object looks as follows: class Post(models.Model): """ Post model """ title = models.CharField(max_length=250) body = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='forum_posts') parent_post = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) time_stamp = models.DateTimeField(default=timezone.now) objects = models.Manager() The serializer for this model is: class PostSerializer(serializers.ModelSerializer): class Meta: model = models.Post fields = ('id', 'title', 'body', 'parent_post', 'author', 'time_stamp') extra_kwargs = {'id': {'read_only': True}, 'author': {'read_only': True}} When returning data for this model, I want to add an extra attribute to each object within the query set called "author_username". The username should be the username belonging to the post's author id. I also want to do this without modifying the model to add another attribute such as "author_username" since this'll be redundant (already have an FK for author). So, ideally, the json for an object would look like: 'post_id': 1 'post_title': 'Example post' 'post_body': 'Example post' 'author_id': 1 'parent_post_id': null 'time_stamp': '2022' 'author_username': 'testUser' How can I go about doing this? Here's my view: class PostList(generics.ListCreateAPIView): permission_classes = [IsAuthenticatedOrReadOnly] queryset = models.Post.objects.all() serializer_class = serializers.PostSerializer -
How to convert db data into json format using python
database table data as input I have the above type of table data (screenshot) and i wanted to convert it into json dictionary using python. I tried my best but unable to create the hierarchy as per my requirement. I want the following json output. output result as json format -
Django Models: Filter a subset of a query set
I have these two models: class InspectionPoint(models.Model): ... review_check = models.BooleanField(default = 0) flight = models.ForeignKey( Flight, related_name='inspection_points', on_delete=models.CASCADE, null=True, blank=True ) ... class ImageSnapshot(models.Model): ... inspection = models.ForeignKey( InspectionPoint, on_delete=models.CASCADE, related_name = 'snapshots' ) flight = models.ForeignKey( Flight, related_name='snapshots', on_delete=models.CASCADE, null=True, blank=True ) ... I already have snapshots queryset with: snapshots = ImageSnapshots.objects.filter(flight=flight) but that gives me all snapshots. I want to filter snapshots that have only (review_check = True) Any idea? -
Django Channels Channels-redis How can I access the database of redis and how can I use it?
I used Django Channels for the first time and Redis for the first time through Channels. I want to use the data stored in the redis server currently in use by django or save it in the redis server. When listing chat rooms, I want to use channels_layer.receive_count to show the number of people who are accessing the chat room. (Like Twitch) When I access the chat room, I want to list the information of the users there. It would be nice if you could tell me how. Thank you! -
Two django projects with common userbase , authentication and sharing of key functionalities
I'm building a Django v3.2 project that requires merging of 2 projects(social app and ecommerce) - both of which are separate open source django projects. The end goal is to share users, posts and a common user registration and authentication process and keep a common database for both. Project 1 has a 5 docker containers(api backend, worker,scheduler, sql db, redis db) and project 2 has 1 docker container(that has a frontend sandbox ecommerce website). I came across this post while searching which is similar : How to make two django projects share the same database Based on the post share above, My core question is : While I'm using 2 separate projects that run their own docker containers, what changes will I have to make so that Registration, Authentication & Users are common Functionalities are shared. Essentially, I would like to import modules from project1-->project2 and project2-->project1 and design additional functionalities as per need. I initially tried copying files from project 2 into project 1 so that the project1 social app and functionality is just extended. But I'm running into all sorts of problems. Here is the question pertaining to the same : Python3.10:ModuleNotFoundError: No module named 'commerce' -
This code worked yesterday for another project, but its showing some error, I cannot get what the error is
what is the error here this is my models.py code, this code worked for another app, but not working in this. why? -
Adding an additional key-value pair to objects in a list before passing it to a Template - Working, but I'm not sure why
New to Django and I wanted to append a key:value pair to each Job object in a Queryset/list before passing it to a template. Researching on here it says you can't just append a field, but rather need to create a new dict or could possibly add attributes or something, but messing around I got it to work great, but logically it seems it shouldn't work, and I worry I may run into problems or data inconsistency somewhere. My "jobs" view gets all Jobs currently not assigned to a User, filters out Jobs based on the current signed in Users listed skillset(a custom field for my User model), and then the functionatily I'm adding is to check the current Users schedule, and add a value "conflict":True if the schedule conflicts so I can highlight it red when rendering the list of jobs to the screen. views.py (abbreviated): def jobs (request): //get all unassigned jobs, and create a list of only jobs where the user has matching skills available = Job.objects.filter(assigned_to__isnull=True).order_by('start_time').all() available = [job for job in available if request.user.is_skilled(job)] //go through each job, make it a dict, and add "conflict":True to it if scheudle confict for job in available: if … -
applying reverse relations with Foreign Key on two different Django models produces incorrect output
Class Job(Base): . . joining_status = models.BooleanField(default=False) drive = models.ForeignKey(Drive, null=True, blank=True) Class Internship(Base): . . joining_status = models.BooleanField(default=False) drive = models.ForeignKey(Drive, null=True, blank=True) Class Drive(xyz): . . . I'm trying to annotate count of jobs & internship (sum) having joining status true for a specific drive id. Drive.objects.filter(id=716).annotate(\ ...: x= Count(Case(\ ...: When(Q(internship__joining_status=True), then=1), output_field = IntegerField()))).values('x') output {'x':0} Drive.objects.filter(id=716).annotate(\ ...: x= Count(Case(\ ...: When(Q(job__joining_status=True), then=1), output_field = IntegerField()))).values('x') output {'x':1} But when I'm combining both together it is producing undesired result. Drive.objects.filter(id=716).annotate(\ ...: x= Count(Case(\ ...: When(Q(job__joining_status=True) | Q(internship__joining_status=True), then=1), output_field = IntegerField()))).values('x') output: {"x":2} // undesired output it should be {'x':1} I tried using multiple when conditions also, but the result was again undesirable. I'm a bit new in django, need help in writing this query.