Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Having trouble adding a hyperlink to a datatable
I have a Django app that uses datatables for a list view of items. Now I am trying to add a hyperlink to the first element of the table which is the primary key for the model I am displaying. The intent is for the link to take you to a detail view for the model instance. I have what I think should work but it is giving me "undefined" for each item in the datatable and throws an error when you click on it. I think it just isn't picking up the ID of the model instance. I've tried any variation of the render function that I can think of but I'm new to javascript so I'm a bit lost. I am pretty confident that my app will work once I get this sorted out. Here is my html: {% extends "app/layout.html" %} {% block content %} <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>Part Requests</title> </head> <body> <h1>Part Orders</h1> <a class="btn btn-info" style="float:right" href="{% url 'New_Order' %}">&nbsp; New Part Order &nbsp;</a> <br /><br /> <div class="table-responsive"> <table id="PartOrders" class="table table-hover"> <thead> <tr> <th>Order #</th> <th>Priority</th> <th>Part Number</th> <th>Part Description</th> <th>Quantity</th> <th>Order Date</th> <th>Unit Name</th> <th>UIC</th> <th>End Item</th> <th>Reason … -
How to run a function in the future using Django based on a condition?
I would like to run a particular function (let's say to delete a post) at a specific time in the future (e.g.: at 10am) only once based on a condition. I am using Django, and I was thinking about using cron or python-crontab, but it seems that these task schedulers can only be used when a particular task has to be executed more than once in the future. As I was trying to use the python-crontab with Django, I also did not find any resources that allow me to execute "this task of deleting a post at 10am tomorrow only if a user does a particular action", for example. Does anyone know if I can still use python-crontab? Or other technology should be used? -
Django: Server Error (500) when trying to add an instance of a model
When I go on localhost:8000/admin and click on "Quotes +ADD" it shows me error 500 instead of the editing interface. "Posts" works well. I just want to know if, without seeing the code, you could just tell me the different possible sources of this problem ? -
django rest framework annotate with ArrayAgg and GROUP BY
I would like to use the django postgres function ArrayAgg, but I would like to also use it with GROUP BY as well. The sql is really easy to write, but I have not been able to get it to work with the ORM or raw sql SELECT field1, ARRAY_AGG(field2) FROM table1 GROUP BY field1 with the orm I would think something like this might work subquery = Subquery( models.Model1.objects .filter(field1=OuterRef('field1')) .values('field2') .aggregate(field3=ArrayAgg('field2')) .values('field3') ) queryset = queryset.annotate(field3=subquery) But it doesn't with a outerref error (I have tried many permutations) and with a raw query I can get it to work, but then it returns all the fields I am guessing due to the RawQueryset and things like defer doesn't work so all fields are queried and returned. rawqueryset = models.Model1.objects.raw( 'SELECT m.id, t.field1, t.field3 ' 'FROM (' 'SELECT field1, array_agg(field2) as field3 ' 'FROM app_table1 ' 'GROUP BY frame_id ' ') t LEFT OUTER JOIN app_table m ON m.field1 = t.frame_id', [] ) serializer = serializers.Model1(rawqueryset, many=True) return Response(serializer.data) Is there a way to do this? -
Objects.filter(" ı wanna add two contains field")
This is search field. But in the views ı cant search on two field. I tried all of this. its not working. its only working in one fields like = Makale.objects.filter(baslik__contains=keyword) makale = Makale.objects.filter(baslik__contains=keyword,icerik_contains=keyword) makale = Makale.objects.filter(baslik_contains=keyword or icerik_contains=keyword) def paylasimlar(request): keyword = request.GET.get("keyword") if keyword: paylasimlar = Makale.objects.filter(icerik__contains=keyword) return render(request, "feed.html", {"paylasimlar": paylasimlar}) paylasimlar = Makale.objects.all() return render(request, "feed.html", {"paylasimlar":paylasimlar}) -
Why do messages with priority don't show up in queue? (Celery)
In Celery, I'm publishing messages to a queue with a specified priority, but they're not showing up in my celery list in my Redis backend or in my flower monitoring. I want to be able to see how many messages are in a queue during any given time so I can see if I need more workers or not. I'm calling my messages using the following code: args = ("2eb89997-7e77-44ee-8bf5-077e5083b7e8", { "body": "hello-world 1", "json": { "time": 1 }, "source": "reddit", "link": "a", "username" : "a"},) app.send_task("main.tasks.save_message_mid_priority", args=args, priority=1) If I call my messages without the priority kwarg, then show up in the default celery queue and I can monitor them. If I do pass it, then I don't. Here's my celery.app from __future__ import absolute_import, unicode_literals from django.conf import settings import os from celery import Celery from kombu import Queue, Exchange # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', '***.settings') app = Celery('***', broker=settings.REDIS_URL) # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all … -
How to insert data in for foreign key attribute from django views?
This is my model with two foreign key attribute: class Count(models.Model): userId = models.ForeignKey(User, on_delete=models.CASCADE) channelId = models.ForeignKey(News_Channel, on_delete=models.CASCADE) rate = models.PositiveIntegerField(default=0) def __str__(self): return self.channelId.name class Meta: ordering = ["-id"] I want to insert some data when user in login , so i write following code in my views.py file for i in range(1,10): obj = Count.objects.filter(userId=request.user.id, channelId=cid) if not obj: o = Count.objects.create(id=Count.objects.all().count() + 1,userId=request.user.id, channelId=i,rate=0) o.save() i += 1 I have channel id from 1 to 10 in my db but I am getting following error: ValueError: Cannot assign "1": "Count.channelId" must be a "News_Channel" instance. Kindly help to insert data. -
How to render a json data into restapi?
I got a JSON response from some url. I have to show that into rest api but i got error. Here is my code views class StoreView(APIView): serializer_class = PostcodeLookupSerializer resp = requests.get('https://api.postcodes.io/postcodes/BN14 9GB') resp_data = resp.json()['result'] result_dic = { 'longitude': resp_data['longitude'], 'latitude': resp_data['latitude'] } result_data = JsonResponse(result_dic) def result(self): json_data = self.resp_data() file_serializer = PostcodeLookupSerializer(json_data, many=True) return Response(file_serializer.data, status=status.HTTP_200_OK) serializer class PostcodeLookupSerializer(serializers.Serializer): postcode = serializers.CharField(required=True) name = serializers.CharField(required=True) and url urlpatterns = [ path('views/', StoreView.as_view(), name='postcode_lookup'),] how to display a json response into restapi? -
How to reference multiple foreignkeys from a model
I would like to reference 2 separate fields from a model into another model. From the code below, i have: First model with the following fields - name, owner and email In the second model, i would like to use the data from name and owner above in the second model but renamed them org (name form group) and org_owner (owner from group) i have tried the below code using related_name. But i get thesame value in both fields. That is a get the name field from group in both the org and org_owner field. Not what i want. class group(models.Model): name = models.CharField(max_length=100, unique=True, blank=False) owner = models.CharField(max_length=100, blank=False) email = models.EmailField(max_length=100, blank=False) class account(models.Model): org = models.ForeignKey('group', on_delete=models.SET_NULL, null=True, related_name='org') org_owner = models.ForeignKey('group', on_delete=models.SET_NULL, null=True, related_name='org_owner') account = models.CharField(max_length=100, blank=False, unique=True) Expected result should be: account.org = group.name account.org_owner = group.owner -
How can I give metatags for the project having django and react js?
I want to give Metatags for the website having django for backend and React.js for frontend.How and where I should give metatags(like in frontend project or backend project) so that I will get the metatags when I hit facebook,linkedin crawler? I tried giving metatags in frontend project on the js file.but the crawler is not rendering metatags from js file.After some research i came to know that Server side rendring should be done for metatags as the google,facebook and linkedin crawler can't read js file.But I have no Idea of how to do SSR? I want to know where i should prerender the render either in django project directory or in react project directory -
Design a database table in sql to store work report
I want to create a project to store the work report of employees working in a company using Django. I am facing some trouble with the Design of the Database tables. The problem is that employee's tasks keep changing and also get exchanged with one another. Tasks are on stats basis. The tables should tell that on a specific date, on how many tasks work has been done and by whom. Also, it needs to store the employee's stats for defined task. One more thing, an employee could work on as many tasks as he wants on a single-day. I wanted the final result to be something like this: ['Date', Total_Tasks, Task_Name['Employee_id','Stats'], Task_Name['Employee_id', 'Stats'], Task_Name['Employee_id', 'Stats']['Employee_id', 'Stats']] And so on The last Task_Name is the example for the Task having multiple workers on it. -
POST large json string from Javascript to Django
I have a small cordova (phonegap) mobile app with simple form. I need select a file, fill other fields and save form. Then I want to send this data later. How I save my form data: form fields in localStorage as json string of serialized array, and file in LocalFileSystem as reader.readAsText() in file (just file with base64 string). How I send data to server: I push base64 string to my serialized array and make an ajax post to server stringified data. My problem: I cant send large json string (when file > 2 MB) to my server, I get an error: code 414, message Request-URI Too Long. How can I fix that? -
Django test - return real object on mock return value
This is my first question regarding Python/Django. I am a Rails developer, and right now I am working with a Django codebase. The thing is, that I am trying to use mock library in order to mock some stuff, here is my code: @mock.patch('namespace.helpers.update') def test_my_method(self, mock): special_offer = mommy.make('airbnb.AirbnbSpecialOffer') airbnb_thread = mommy.make('airbnb.Thread') ticket = mommy.make('mailbo.Ticket', airbnb_thread=airbnb_thread) mock.update_or_create_special_offer.return_value = special_offer helpers.my_method({'special_offer': 10}, ticket) self.assertEqual(mock.called, True) The code under test, make an update on my the line mock.update_or_create_special_offer.return_value = special_offer return <MagicMock name='update()' id='4562879184'> and not a special_offer object. How I can fix it? Thank in advance -
Django image has no file associated even though I have blank and null
When a user signs up I used to have it so that an image got applied to that users account. But due to file locations I cannot have it like that anymore, so I am trying to have it so when a user signs up, it leaves the image field blank, so I can render a fake default image on the template. But when a user signs up, or view's there profile or logs in it throws an The 'image' attribute has no file associated with it. error. I thought I could get around this by having blank=True and null=True, but for some reason it keeps throwing this error. Models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(verbose_name='Profile Picture', upload_to='profile_pictures', blank=True, null=True) def __str__(self): return f'{self.user.username} Profile' def save(self, force_insert=False, force_update=False, using=None): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) Views: def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) review = Post.objects.filter(live=False, author=request.user) post = Post.objects.filter(live=True, author=request.user) context = { 'u_form': … -
Reverse for 'post-detail' with arguments '('',)' not found
In django I have issues to understand the changes while handling the data transfer to templates with the {{}} ...it seem to change all the time. Why ? Here my code gives me the error: Reverse for 'post-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P[0-9]+)$'] My view seem alright so is my template. And I don't know why I should change my url as it was working fine.. ### app views class PostDetailView(LoginRequiredMixin, DetailView): model = Post template_name = 'blog/post_detail.html' def get_context_data(self,*arg, **kwargs): context = super().get_context_data(**kwargs) form = CommentForm() context['form'] = form return context def post(self, request,*arg, **kwargs): if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): form.save() else: form = CommentForm() context ={ 'form':form } return render(request, self.template_name, context) ### templates : <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form | crispy }} <button class="btn btn-primary" type="submit" > submit </button> <input value=" fuck" type="submit" onclick="{% url 'post-detail' post.id %}"> </form> #### urls : path('post/<int:pk>', PostDetailView.as_view(), name='post-detail'), I tried every help post online but without success. I just want to be able to post comments under the blog post... If someone knows which direction I should take that would be great! -
Stripe payments is not being created in django. It says token is submitted successfully, but it does not show in stripe account
when i created a stripe checkout form, i set up everything as the docs said. When i submit the form (test keys), it says that the token was created successfully, but it does not show in the stripe account dashboard. settings.py STRIPE_SECRET_KEY = "itsthestripesecretkeyfromaccount" STRIPE_PUBLISHABLE_KEY = "itsthestripepublishkeyfromaccount" views.py def checkout(request, **kwargs): item = Shop.objects.filter(id=kwargs.get('pk', "")).first() stripe.api_key = settings.STRIPE_SECRET_KEY publishKey = settings.STRIPE_PUBLISHABLE_KEY if request.method == 'POST': token = request.GET.get['stripeToken'] # Using Flask charge = stripe.Charge.create( amount=10.00, currency='usd', description="Testing", source=token, ) context= {'publishKey':publishKey, 'item':item} return render(request,"checkout/checkout.html",context) checkout.html <html><head> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" rel="stylesheet"> <style media="screen"> body, html { height: 100%; background-color: #f7f8f9; color: #6b7c93; } *, label { font-family: "Helvetica Neue", Helvetica, sans-serif; font-size: 16px; font-variant: normal; padding: 0; margin: 0; -webkit-font-smoothing: antialiased; } button { border: none; border-radius: 4px; outline: none; text-decoration: none; color: #fff; background: #32325d; white-space: nowrap; display: inline-block; height: 40px; line-height: 40px; padding: 0 14px; box-shadow: 0 4px 6px rgba(50, 50, 93, .11), 0 1px 3px rgba(0, 0, 0, .08); border-radius: 4px; font-size: 15px; font-weight: 600; letter-spacing: 0.025em; text-decoration: none; -webkit-transition: all 150ms ease; transition: all 150ms ease; float: left; margin-left: 12px; margin-top: 28px; } button:hover { transform: translateY(-1px); box-shadow: 0 7px 14px rgba(50, 50, 93, .10), 0 3px … -
Placement of django abstract modal
In a django project i have some apps which uses the same address modal, so instead of setting a foreign key across different apps, i decided to use an abstract model instead. class Address(models.Model): pass class Meta: abstract = True class Customer(Address): pass My question is, where should i define this abstract Address model, since it's not related to a specific app, and will be used in different models in different apps -
How to render_to_pdf with context of specific model object
I'm attempting to render a PDF and populate the template with specific data from the object that is being viewed. I'm using xhtml12pdf / pisa. I've successfully rendered a generic (unpopulated) PDF, however when I add logic to populate a specific object's data, my context is being returned however the pdf is no longer being rendered. views.py class GeneratePdf(DetailView): model = Request template_name='request_response/response.html' def get(self, request, *args, **kwargs): context = super(GeneratePdf,self).get(request,*args,**kwargs) return context pdf = render_to_pdf('request_response/response.html',context) if pdf: response = HttpResponse(pdf,content_type='application/pdf') filename = "PrivacyRequest_%s.pdf" %("1234") content = "inline; filename='%s'" %(filename) response['Content-Disposition'] = content return response return HttpResponse("Not Found") -
Serialize User Instance for use on other function
I'm trying to pass a User instance over to my other function but I can't make it happen. The User instance is not JSON serialiazeable so I googled a bit about it and found that you could use an in-built serializer in Django. However I still can't make it work. Views 1: from django.core import serializers userdata = request.user serialized_obj = serializers.serialize('json', userdata) SubtaskUpdate("2464c7ca-7f14-11e9-b4c2-b870aca6d744", serialized_obj) Views 2: def SubtaskUpdate(taskid, user): base_dir = settings.BASE_DIR uniquefolder = os.path.join(base_dir, 'var/taskqueries').replace("\\", "/") os.chdir(uniquefolder) logfilnavn = str(uuid.uuid4()) # Variabel til filnavn logfile = open(logfilnavn, 'w') # Åbner fil med navn fra forrige variabel proc=subprocess.Popen(['golemcli', '--mainnet', "tasks", 'subtasks', taskid, "--json"], universal_newlines=True, stdout=logfile, stderr=logfile) proc.wait() logfile.close() taskre = Task(TaskID=taskid, User=user) taskre.save() with open(logfilnavn) as json_file: print(json_file) json_object = json.load(json_file) for node in json_object['values']: Node = node[0] ID = node[1] Time = node[2] Status = node[3] h = NodesData.objects.get(Node=Node) a = Subtask(SubtaskID=ID, Country=h.NodeCountry, City=h.NodeCity, Cores=h.Node_Cores, Disk=h.Node_Disk, Memory=h.Node_Memory, OS=h.Node_OS, SubtaskNode=Node, SubtaskStatus=Status, Task=taskre) a.save() os.remove(logfilnavn) Model: class Task(models.Model): TaskID = models.CharField(max_length=128) User = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) class Subtask(models.Model): SubtaskID = models.CharField(max_length=128, default="Awaiting Query") SubtaskNode = models.CharField(max_length=24, default="Awaiting Query") SubtaskStatus = models.CharField(max_length=15, default="Awaiting Query") Country = models.CharField(max_length=25, default="Awaiting Query") City = models.CharField(max_length=25, default="Awaiting Query") OS = models.CharField(max_length=15, default="Awaiting Query") Cores = … -
Create a form(webpage). Fill using the LAN that the college provides. NO INTERNET. I want all the data that they enter to be saved?
I have to create a form using HTML. The form will be filled by students using their computers in the computer lab. The webpage will not be available on internet. I have to deploy it on a local host. also the data that students enter has to be saved. Guide me through this? -
I renamed an html template but django template loader keeps searching for the old file
I'm a complete python/django noob. I had an html template file called book_detail.html, and the app was running fine. I renamed the file to book_view.html and i get an error. My question is, what is causing this, and is there a way for me to tell django/python to rebuild the project when there's a template name change? I ran manage.py runserver but it doesn't seem to picking up the new name. Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: PycharmProjects/my_proj/my_proj/books/templates/books/book_detail.html (Source does not exist) django.template.loaders.app_directories.Loader: PycharmProjects/my_proj/venv/lib/python3.6/site-packages/django/contrib/admin/templates/books/book_detail.html (Source does not exist) django.template.loaders.app_directories.Loader: PycharmProjects/my_proj/venv/lib/python3.6/site-packages/django/contrib/auth/templates/books/book_detail.html (Source does not exist) django.template.loaders.app_directories.Loader: PycharmProjects/my_proj/my_proj/books/templates/books/book_detail.html (Source does not exist) -
GET http://127.0.0.1:8000/dist/bundle.js net::ERR_ABORTED 404 (Not Found), despite compiling successfully.(vuejs+django webapp)
I am working on the cutecats tutorial and have trouble while integrating vue+django. I get no errors on compilation, the bundle.js is created and I can see it in my IDE, but the bundle returns a 404 error on browser. Here is the tutorial that I have followed - https://medium.com/@jrmybrcf/how-to-build-api-rest-project-with-django-vuejs-part-i-228cbed4ce0c Here is my webpack.config.js var path = require('path') var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') var WriteFilePlugin = require('write-file-webpack-plugin') module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, './dist'), publicPath: '/dist/', filename: 'bundle.js' }, plugins: [ new BundleTracker({filename: 'webpack-stats.json'}), new WriteFilePlugin() ], module: { rules: [ { test: /\.css$/, use: [ 'vue-style-loader', 'css-loader' ], }, { test: /\.scss$/, use: [ 'vue-style-loader', 'css-loader', 'sass-loader' ], }, { test: /\.sass$/, use: [ 'vue-style-loader', 'css-loader', 'sass-loader?indentedSyntax' ], }, { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { // Since sass-loader (weirdly) has SCSS as its default parse mode, we map // the "scss" and "sass" values for the lang attribute to the right configs here. // other preprocessors should work out of the box, no loader config like this necessary. 'scss': [ 'vue-style-loader', 'css-loader', 'sass-loader' ], 'sass': [ 'vue-style-loader', 'css-loader', 'sass-loader?indentedSyntax' ] } // other vue-loader options go here } }, { … -
Django Suspicious File Operation Error when uploading image
On my profile page, a user gets assigned a default image automatically when they sign up. But after changing the way static and the media folders work, it gives me the following error: django.core.exceptions.SuspiciousFileOperation: The joined path (/static/public/images/default.jpg) is located outside of the base path component (/mnt/c/Users/maxlo/Documents/apps/adinl/adinl/media). I think that it is trying to find the image in media, but it has since been moved into static/public/images/default.jpg I have tried the following: https://stackoverflow.com/a/22020405/7355857, but doesn't seem to be working. If anyone has an idea on how to fix this it would be great. Models: from django.db import models from django.contrib.auth.models import User from django.core.files import File from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='/static/public/images/default.jpg', upload_to='profile_pictures', verbose_name='Profile Picture') def __str__(self): return f'{self.user.username} Profile' def save(self, force_insert=False, force_update=False, using=None): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) Settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/') MEDIA_URL = '/media/' File Structure: -
creat Api end point of two nested models at once
I'm creating a django api application, i have three main apps (Post, Anomaly, Event), a user can creat an anomaly or event (witch are nested models of post). All i did for now is using generic views and mixins, so i can list create update and delete each model for him self, but now i want with one request create an anomaly or event (not creating the post then creating the event). Post Models class Post(models.Model): post_owner = models.ForeignKey(MyUser, on_delete=models.CASCADE) description = models.TextField(max_length=255) city = models.ForeignKey(City, related_name='location', on_delete=models.CASCADE) longitude = models.CharField(max_length=255) latitude = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) Post Serializers class PostSerializer(serializers.ModelSerializer): comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True) reactions = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Post fields = '__all__' Post ApiViews class PostAPIView(mixins.CreateModelMixin, generics.ListAPIView): lookup_field = 'pk' serializer_class = PostSerializer def get_queryset(self): qs = Post.objects.all() return qs def perform_create(self, serializer): serializer.save(post_owner=self.request.user) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def get_serializer_context(self, *args, **kwargs): return {"request": self.request} class PostRudView(generics.RetrieveUpdateDestroyAPIView): lookup_field = 'pk' queryset = Post.objects.all() serializer_class = PostSerializer Event Model class Event(models.Model): post = models.ForeignKey(Post, related_name='event', on_delete=models.CASCADE) approved_by = models.ForeignKey(MyUser, related_name='approvedBy', on_delete=models.CASCADE, null=True) approved_at = models.DateTimeField(null=True) max_participants = models.IntegerField() starts_at = models.DateTimeField() Event Serializers class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields … -
Django - Count related with filter
I have a model called Article and I have a model called Comment which has a foreignkey to Article. I want to count from a Article queryset all comments in that queryset. Example: I have a queryset with 5 articles and every article has 3 comments except for one. -> This should return 12. Another example: One article has 3 comments and another one has 5 and other articles have no comments. -> This should return 8. I tried it with: Article.objects.all().annotate(comments_count=Count("comment", filter=Q(is_deleted=False))).comments_count