Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Calculating two integers fields in django
I want to calculate these fields and want output for example (budget - Expense) (budget + Expense) (budget * Expense). how could i do that. Class calculate(models.Model): budget = models.IntegerField(default=0) Expense = models.IntegerField(default=0) -
Circular import error while importing urls file of another app in main app urls
I have created an app in djano with name user, and inside that user app , there is a file called urls.py, it contains various api_end points. Now I want to import this urls.py of app.py inside the urls.py file created by django project. I am getting circular import error. this is urls.py file created by django-admin urlpatterns = [ path('admin/', admin.site.urls), url(r'^api/v1/', include('user.urls')), ] and this is urls.py file created inside user app urlpatterns = [ url(r'^login/?$', token_handling.CustomTokenObtainPairView.as_view(), name='login'), ] -
Setup docker volume for django logger
I have a Django 2.2 application and want to serve the application using Docker. I have the Django logger setup as FILE_LOCATIONS = { 'debug': '{}/logs/{}/app/{}'.format('/var/log/app', 'QCG2', 'debug.log'), 'error': '{}/logs/{}/app/{}'.format('/var/log/app', 'QCG2', 'error.log'), 'info': '{}/logs/{}/app/{}'.format('/var/log/app', 'QCG2', 'info.log') } LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime}: ~{pathname} (line: {lineno}):: {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {message}', 'style': '{', }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': FILE_LOCATIONS['debug'], 'formatter': 'verbose', 'when': 'midnight', 'interval': 1, 'backupCount': 0, }, 'console': { 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'loggers': { 'app': { # Common logger, log app 'handlers': ['console', 'file'], 'level': 'DEBUG', 'propagate': True, }, 'plan_change': { # Log plan change process 'handlers': ['console', 'file'], 'level': 'DEBUG', 'propagate': True, }, } } and docker-compose.yml file as version: '3' services: nginx: image: nginx:alpine container_name: "myapp-staging-nginx" ports: - "8000:80" volumes: - .:/app - ./configs/docker/nginx:/etc/nginx/conf.d depends_on: - web web: build: . container_name: "myapp-staging-dev" command: ["./scripts/docker/wait_for_it.sh", "db:5433", "--", "./scripts/docker/docker_start.sh"] volumes: - .:/app depends_on: - db # For database - redis # For celery broker db: image: mysql:8.0 container_name: "myapp-staging-mysql-db" env_file: - configs/docker/env/mysql_env.env ports: - "5433:5432" volumes: - myapp_staging_db_volume:/var/lib/mysql/data redis: image: "redis:alpine" celery: build: . command: celery -A qcg … -
Angular router guard with Django
I am using django authentication, I want to use angular router guards when not signed in. So that it reroutes to login page if not logged in. I have tried to setup as angular usually would with router guards, but this routes to the url without a trailing slash which doesn't work with Django. I have fixed it so it keeps the trailing slash, but this doesn't route to the Django page, it seems its looking for a Angular page. But if it type in the url for the Django login page that still works. Auth Guard: checkLogin(url: string): boolean { if (this.authService.isLoggedIn) { return true; } this.authService.redirectUrl = url; this.router.navigate(['/accounts/login/.']); return false; } app-routing module: { path:"", component: ProjectHomeComponent, canActivate : [AuthGuard], children: [ { path: '', children: [ { path: 'view', component: ProjectViewComponent }, { path: 'seeManage', component: ProjectManageComponent }, { path: '**', component: PagenotfoundComponent } ] } ] } Expect to be routed to django login page, not routed to django login page -
I want save data in sqlite Database, My Query not working in webpage But same code wroking fine in Django Shell
I am trying to add some data via Views.py but it not working but the same code working in django shell. My Code : username = request.POST['username'] bp = request.POST['bp'] bs = request.POST['bs'] height = request.POST['height'] weight = request.POST['weight'] temp = request.POST['temp'] datasaved = PatTest(Patient= Patient.objects.get(username=str(username)), BS=int(bs), BP=int(bp), PatHeight=float(height), PatientWeight=float(weight), BMI=BMICal(height, weight), TEMPA=int(temp)) print("Test") datasaved.save() -
Django - How to dynamically create signals
I'm working on a model Mixin which needs to dynamically set signals based on one attribute. It's more complicated but for simplicity, let's say the Mixin has this attribute: models = ['app.model1','app.model2'] This attribute is defined in model which extends this mixin. How do I can register signals dynamically? I tried to create a classmethod: @classmethod def set_signals(cls): def status_sig(sender, instance, created, *args, **kwargs): print('SIGNAL') ... do som things for m in cls.get_target_models(): post_save.connect(status_sig,m) My idea was to call this method somewhere in class automatically (for example __call__ method) but for now, I just tried to call it and then save the model to see if it works but it didn't. from django.db.models.signals import post_save print(post_save.receivers) Realestate.set_signals() print(post_save.receivers) r = Realestate.objects.first() r.status = 1 r.save() output [] [((139967044372680, 46800232), <weakref at 0x7f4c9d702408; dead>), ((139967044372680, 46793464), <weakref at 0x7f4c9d702408; dead>)] So you see that it registered those models but no signal has been triggered after saving the realestate. Do you know how to make it work? Even better without having to call method explicitely? EDIT: I can't just put the signals creation inside mixin file because models depends on the string in child model. -
Can't Add/Accept and Decline/Cancel Friend requests on Django
Able to Send Friend requests successfully but responding to the requests are an issue. When you press Accept to Add, the button is removed but the Friend isn't added or when you press Cancel to Decline, nothing happens. Tried adding a forms class Add_Friend(forms.ModelForm): model = UserProfile def add_friend(request, user_profile): request.notification_set.get(type=Notification.FRIEND_REQUEST, sender=user_profile.user.username).delete() request.friends.add(user_profile) user_profile.friends.add(self) request.friend_requests.remove(user_profile) noti = Notification.objects.create(owner=user_profile, type=Notification.ACCEPTED_FRIEND_REQUEST, sender=self.user.username) user_profile.notification_set.add(noti) return self.friends.count() class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(blank=True, max_length=128) friends = models.ManyToManyField('self', blank=True, related_name='friends') friend_requests = models.ManyToManyField('self', blank=True, related_name='friend_requests') def send_friend_request(self, user_profile): self.friend_requests.add(user_profile) noti = Notification.objects.create(owner=self, type=Notification.FRIEND_REQUEST, sender=user_profile.user.username) self.notification_set.add(noti) return self.friend_requests.count() def add_friend(self, user_profile): self.friend_requests.remove(user_profile) self.notification_set.get(type=Notification.FRIEND_REQUEST, sender=user_profile.user.username).delete() self.friends.add(user_profile) user_profile.friends.add(self) noti = Notification.objects.create(owner=user_profile, type=Notification.ACCEPTED_FRIEND_REQUEST, sender=self.user.username) user_profile.notification_set.add(noti) return self.friends.count() def cancel_friend_request(self, user_profile): self.friend_requests.remove(user_profile) self.notification_set.get(type=Notification.FRIEND_REQUEST, sender=user_profile.user.username).delete() noti = Notification.objects.create(owner=user_profile, type=Notification.DECLINED_FRIEND_REQUEST, sender=self.user.username) user_profile.notification_set.add(noti) return self.friend_requests.count() def __str__(self): return self.get_first_name() #Takes you to the userprofile page def get_absolute_url(self): return "/users/{}".format(self.id) @method_decorator(login_required, name='dispatch') class SendFriendRequestView(View): def get(self, request, *args, **kwargs): profile_id = request.GET.get('profile_id') requester_id = request.GET.get('requester_id') target = UserProfile.objects.get(id=profile_id) requester = UserProfile.objects.get(id=requester_id) target.send_friend_request(requester) message = 'Friend request to {} sent!'.format(target.visible_name) messages.info(request, message) return redirect('profile', username=target.user.username) @method_decorator(login_required, name='dispatch') class CancelFriendRequestView(View): def cancel_friend_request(request, id): if request.user.is_authenticated(): user = get_object_or_404(User, id=id) frequest, created = FriendRequest.objects.filter( from_user=request.user, to_user=user).first() frequest.delete() return HttpResponseRedirect('/users') @method_decorator(login_required, name='dispatch') class AddFriendView(View): def … -
Django Forms Not Rendering In HTML
I am finding it difficult to show django forms in html template. The django form fails to render in the template. I am using class base view and below are my codes for views.py,urls.py, models.py and the html template: views.py class Home(CreateView): models = Blog queryset = Blog.objects.filter(publish = True) template_name='index.html' fields = '__all__' urls.py ... urlpatterns=[ path('', Home.as_view(), name='index'), ] models.py ... Continent = ( ('select continent', 'Select Continent'), ('africa', 'Africa'), ('europe', 'Europe'), ('north america', 'North America'), ('south america', 'South America'), ('asia', 'Asia'), ('australia', 'Australia'), ('Antarctica', 'Antarctica'), ) class Blog(models.Model): name= models.CharField(max_length = 200) company= models.CharField(max_length = 200) post = models.CharField(max_length = 200) author= models.ForeignKey('auth.User', on_delete = models.PROTECT) mantra= models.CharField(max_length = 200, help_text='make it short and precise') continent = models.CharField(choices= Continent, default= 'select continent', help_text='help us to know you even more', max_length=50) publish = models.BooleanField(default =True) def __str__(self): return self.name def get_absolute_url(self): # new return reverse('post_detail') index.html {% extends "base.html" %} {% load static %} {% block content %} <body class="loading"> <div id="wrapper"> <div id="bg"></div> <div id="overlay"></div> <div id="main"> {{form.as_p}} {% include "partials/_footer.html" %} </div> </div> </body> {% endblock %} Any assistance will be greatly appreciated. Thanks. -
local variable 'submission' referenced before assignment
I encounter this error for my django project. my app is called "scoresubmission" basially i have a feature in the website to allow user download report. So in my views.py file i have report function and import report.py file, where it shows how report is built It shows the error happens in this line of code: submission=Submission.objects.get(month=month,year=reportyear,program=program) Views.py def report(request): from scoresubmission.report import reportA, reportB, reportC reportType = request.POST["reportType"] reportYear = int(request.POST["reportYear"]) if reportType == 'a': report_content = reportA(reportYear) response = HttpResponse(report_content, content_type="text/csv") response['Content-Disposition'] = 'inline; filename=5SAuditYearlySummaryReport_%d.xlsx' %reportYear report.py where it has the relevant code for facility in facilities: worksheet.write(row,col,facility.name,facility_format) for i in range(12): # 12 months month=i+1 programs=Program.objects.filter(facility_id=facility.id) avg_totalscore=0 count=1 for program in programs: print(program) try: submission=Submission.objects.get(month=month,year=reportyear,program=program) print(submission) avg_score=Result.objects.filter(submission=submission).aggregate(Avg('NewScore')) #print avg_score.get('NewScore__avg') avg_totalscore=(avg_totalscore + avg_score.get('NewScore__avg'))/count count=count+1 except submission.DoesNotExist: pass #print avg_totalscore if avg_totalscore!=0: worksheet.write(row,i+3,avg_totalscore,red_format) else: worksheet.write(row,i+3,'-',red_format) Traceback (most recent call last): File "C:\Users\CHLOZHAO\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\CHLOZHAO\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\CHLOZHAO\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\CHLOZHAO\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\D Drive\5S Audit Website\my5saudit\scoresubmission\views.py", line 185, in report report_content = reportA(reportYear) File "C:\D Drive\5S Audit Website\my5saudit\scoresubmission\report.py", line 79, … -
DJANGO > 2.2 - Unique together on foreign keys A, B OR foreign keys A, B, C
In Django 2.2, you can get rid of unique_together in favor of a constraints list with a UniqueConstraint class that can be handy because it has a condition arg. MyObject has three foreign keys, one is optional. class MyObject(ModelBase): parent=... # mandatory source=... # mandatory subsource=... # optional class Meta: constraints = [ models.UniqueConstraint( fields=["parent", "source", "subsource"], name="unique_subsource" ), models.UniqueConstraint( fields=["parent", "source"], condition=models.Q(subsource=None), name="unique_source", ), ] Imagine I try to create successively the following objects and the expected validation: parent source subsource valid? 1. 1. 1. yes 1. 1. 2. yes 1. 1. - yes 1. 1. - no 1. 1. 3. yes 1. 2. - yes ... So I wrote two tests: def test_unique1(self): """ unique parent/source/subsource """ parent = ParentFactory() source = SourceFactory() subsource = SubsourceFactory() MyObjectFactory(parent=parent, source=source, subsource=subsource) myobj = MyObjectFactory.build(parent=parent, source=source, subsource=subsource) self.should_raise_validation_error(myobj) def test_unique2(self): """ unique parent/source """ parent = ParentFactory() source = SourceFactory() subsource = SubsourceFactory() MyObjectFactory(parent=parent, source=source) myobj = MyObjectFactory.build(parent=parent, source=source) self.should_raise_validation_error(myobj) But the latter does not raise any validation error. -
Django utf-8 urls
I have a Django app that works fine on localhost.even for utf-8 URL path.but when I use it in production it gives me an error: 2019-09-01 14:32:09.558237 [ERROR] [12257] wsgiAppHandler pApp->start_response() return NULL. Traceback (most recent call last): File "/home/medualla/virtualenv/project/3.7/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 139, in call set_script_prefix(get_script_name(environ)) File "/home/medualla/virtualenv/project/3.7/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 179, in get_script_name script_url = get_bytes_from_wsgi(environ, 'SCRIPT_URL', '') or get_bytes_from_wsgi(environ, 'REDIRECT_URL', '') File "/home/medualla/virtualenv/project/3.7/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 204, in get_bytes_from_wsgi return value.encode('iso-8859-1') UnicodeEncodeError: 'latin-1' codec can't encode characters in position 1-6: ordinal not in range(256) this error occurs when i try a url like http://meduallameh.ir/صفحه the only answer I got was that problem with the webserver. I deployed it on a shared host and I asked them and they told me that web server supports utf-8. now I need some help to fix this problem. -
setting image src from jquery with attr() from a django static directory
I am new to django and I want to set an image from a static directory to an <img> tag via jQuery. I have the below logic: <img id="A"> function showProfile(person) { $("#A").attr("src", "main/images/portrait/" + person + "1.jpg"); } However, when running the above, the image does not show. with Django static files I usually do: <img id="A" src="{% static "main/images/portrait/whatever.jpg" %}"> However, I want to get an image dynamically via jQuery how can this be done? -
How to create a dictionary from many different sources?
I want to create a dictionary just like this example : {"('Open', 'Jaipur', 'Pune')": [{1: [12, 12, 12, 12]}]} Now, every word you see here I have it but in either a dataframe, or in a list. The first word 'Open' is the truck-type which I can get by fetching it from a dataframe by using truck["Category"], the second and third are names of places, which I have stored in my items' list, and can get by using items[0].origin and items[0].destination. Also, my items list is as such [12,12,12,12]. Now, I want to recreate this as a single dictionary, with all these together, and it should always have 1 as the key. I tried something like this, but I don't get anywhere near the final output: open_list_key = [truck["Category"],items[0].origin,items[0].destination] open_list_value = items open_list = {open_list_key:open_list_value} -
Can't return QuerySet filter to html page
i want filter employee form department and site by user filter and submit i post value form html to definition in views.py @csrf_exempt def empFil(request): dep = request.POST.get('dep',None) site = request.POST.get('site',None) print(dep) print(site) fil = TB_employee.objects.filter(dep_id = dep, site_id = site).select_related('site_id','dep_id','pos_id','sec_id') print(fil) return render(request,'app/employee.html',{'fil':fil}) this command line 21 2 <QuerySet [<TB_employee: TB_employee object (4892)>, <TB_employee: TB_employee object (4916)>]> in employee.html {% for e in fil %} <tr> <td>{{e.en}}</td> <td>{{e.name_th}}</td> <td>{{e.surname_th}}</td> <td>{{e.name_eng}}</td> <td>{{e.surname_eng}}</td> <td>{{e.pos_id.pos_name}}</td> <td>{{e.dep_id.dep_name}}</td> <td>{{e.site_id.site_name}}</td> <td>{{e.hire_date}}</td> <td>{{e.sec_id.sec_name}}</td> <td>{{e.emp_type}}</td> <td>{{e.emp_status}}</td> <td>{{e.emp_email}}</td> <td>{{e.budget}}</td> </tr> {% endfor %} in html page cannot show data -
Django Credit System
I am making a system where users to sign up my system they have to buy credit and then I need to upload the credit in their account. When they make some actions on web site. I will decrease their credit number. How can I do that? I had try to add a field in "user model" called "credit number". But the problem is that for me: when two user make request at the same time to "credit number" section I need to apply both request respectively. I read about transaction. Do you suggest me a way to do it? -
Trying in make insert query using cursor in django and can not get rid off this error TypeError: not all arguments converted during string formatting
I am trying to make aan insert query using cursor in Django, but this error shows I searched for more than one solution but nothing helped the error is: sql = sql % tuple('?' * len(params)) TypeError: not all arguments converted during string formatting I tried to use '%s' instead of '?' but it didn't work def insert_DTARFDE2003SYD0827(sourcePE,sourceInterFace,targetPE,targetInterFace): params = (sourcePE, sourceInterFace,targetPE,targetInterFace) if sourcePE!=None and sourceInterFace!=None and targetPE!=None and targetInterFace!=None: sql=" insert into DTA.RFDE2003SYD0827 values ( '?','?',NULL,NULL,NULL,'?','?' " with connections['DataAdmin'].cursor() as cursor: cursor.execute(sql,params) The error is: sql = sql % tuple('?' * len(params)) TypeError: not all arguments converted during string formatting -
I cannot make my NRF24L01 communication(raspberry pi to many arduinos) work consistently
I am using a Master-Slave protocol and the NRF24L01 module for my Raspberry Pi to Arduino communication. In my case the Raspberry Pi is the master and it requests via a specific pipe(hex address) a radio response from one of Arduinos in the network. I am also using Django and Celery for my project, so I wrote a celery @task that gathers the response information from the Arduino. My problem is that most of the time when I change the pipe in order to talk to another Arduino, the radio signal is not felt by the Arduino so the request from the RPi just times out. My bet is that I do not "clean" the connection properly in the @task after I'm done with the receiving of the information. I have tried many different things but none were of success. Any help is appreciated. I thought maybe it had something to do with the GPIO.cleanup() function at the and of my task, but that didn't fix my problem. I have tested over and over again to see if I could make up some kind of pattern in the loss of connection but I was unsuccessful. I have also seen that … -
How do i update boolean field on Django model?
I have implemented a view that is supposed to update two boolean fields on a Django model i.e is_published and submitted. However , currently, the view is only able to update the first boolean field(is_published) and leaves out the second one(submitted). What am i doing wrong and how can I implement a solution that updates both fields at the same time? Here is my code Model class Course(models.Model): is_published = models.BooleanField(default=False) submitted = models.BooleanField(default=False) View class UpdateVideoAPIPublishView(generics.UpdateAPIView): """ Update course """ permission_classes = (IsAuthenticated,) renderer_classes = (CourseJSONRenderer,) serializer_class = CourseSerializer def update(self, request, *args, **kwargs): course = get_object_or_404( Course, slug=self.kwargs['slug']) if not course.is_published: course.is_published = True course.submitted = False course.save() return Response( {"message": "Course updated succesfully"}, status=status.HTTP_201_CREATED) raise serializers.ValidationError( 'Course already published' ) -
How to read google calendar events of user after getting access token?
I want to get google calendar events of my users in django and I wrote the following code. This code works and saves access token of user but I don't know what I should to do to get google calendar events of user after it. I had some problem before this and asked it in this question and tried to solve it and now I am here. can some one help me? in url: url(r'^new_event/$', views.new_event, name="new_event"), url(r'^oauth2_callback', OAuth2CallBack.as_view(), name='oauth2_callback'), url(r'^access_to_google_calendar$', views.access_to_google_calendar, name="access_to_google_calendar"), in view: def access_to_google_calendar(request): # Following line is for getting google calendar events of user to show him flow = OAuth2WebServerFlow(settings.CLIENT_ID_CALENDAR, settings.CLIENT_SECRET_CALENDAR, scope='https://www.googleapis.com/auth/calendar', redirect_uri=settings.REDIRECT_URI_CALENDAR) generated_url = flow.step1_get_authorize_url() return HttpResponseRedirect(generated_url) class OAuth2CallBack(View): def get(self, request, *args, **kwargs): code = request.GET.get('code', False) if not code: return JsonResponse({'status': 'error, no access key received from Google or User declined permission!'}) flow = OAuth2WebServerFlow(settings.CLIENT_ID_CALENDAR, settings.CLIENT_SECRET_CALENDAR, scope='https://www.googleapis.com/auth/calendar', redirect_uri=settings.REDIRECT_URI_CALENDAR) credentials = flow.step2_exchange(code) http = httplib2.Http() http = credentials.authorize(http) credentials_js = json.loads(credentials.to_json()) access_token = credentials_js['access_token'] # Store the access token in case we need it again! username = request.user.username with open('token.csv', 'w') as file: fieldnames = ['user', 'token'] writer = csv.DictWriter(file, fieldnames=fieldnames) writer.writeheader() writer.writerow({'user': username, 'token': access_token}) request.session['access_token'] = access_token return redirect('new_event') def post(self, request, … -
How can I count the number of download of a static file on my django website?
I am beginner with django, and I would to create on my website, a library which allows to dowload executables files, wich I created myself. And I would like to count how many times each file has been downloaded. So I thought to a middleware, knowing that I am able to make a middleware which counts and displays the number of times a page has been viewed : def stats_middleware (get_response): def middleware (request): try : p = Stat.objects.get(url = request.path) p.views_number = F('views_number')+1 p.save except Stat.DoesNotExist : p = Stat.objects.create(url= request.path) response = get_response(request) response.content += bytes( "cette page a été vue {} fois.".format(p.views_number), "utf8" ) return response return middleware And I thought that, if I managed to open the download in a new page, I could count the number of times it appears and thus the number of downloads of the file. But I did not manage to open the download in another tab. if you have any idea what to do, do not hesitate to let me know, thanks in advance, and sorry for my english which is not very good. -
Django 2.2+ call rest api, filtering on list of ids
How can I use the in operator for filtering on a list of ids for the results of a ViewSet in the django rest framework? A solution to the same question was found a few years ago, however the accepted solution no longer works: Call django rest API with list of model ids The viewset could for example be defined as: class MarkerViewSet(viewsets.ModelViewSet): queryset = Marker.objects.all() serializer_class = MarkerSerializer -
Replace placeholders in text with input fields with django templates
I'd like to render a page with django templates that is able dynamically place input fields based on the provided text templates. An example i found but with vue found here Given a text like My name is {name}, I am {age} years old. I live in {location} I'd like to replace {name}, {age}, {location} with input fields. -
what are the chances for this random unique Id generator to collide?
i want to know what are the chances for this unique id generator to collide https://github.com/vejuhust/blog-code/blob/master/python-short-id-generator/short_id_v5.py i wanted to generate a unique url for my Django project. is it going to be safe to use. i am a beginner in python and Django. -
the site took too long to respond
I deployed my django app on iis using wfastcgi but the app doesn't load on any browser. In mozilla the app keeps trying to connect on and on meanwhile in chrome I get the app took too long to respond. I deployed my app from the anaconda environment and I cannot see any error. Any tips to fix this issue? -
Django: AttributeError: 'Q' object has no attribute 'count'
I try to get the count of all attendees. I created the following for loop and query set. However, I always get the error AttributeError: 'Q' object has no attribute 'count'. Do you have an idea how to fix that? # Get count of attendees per ticket and then combine these tickets = Ticket.objects.filter(event=3) count = 0 for ticket in tickets: new_count = ticket.attendees.filter=Q( canceled=False, order__status__in=( OrderStatus.PAID, OrderStatus.PENDING, OrderStatus.PARTIALLY_REFUNDED, OrderStatus.FREE, ), ).count() count += new_count print(count)