Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: custom Action with date parameter not working
I have the following code in Python Django: @action(detail=True, methods=['get'], url_path=r'by_date') def get_meal_by_date(self, request, meal_date=date.today): print(meal_date) meals_by_date = Meal.objects.filter( owner=self.request.user, mealTimestamp__day=meal_date.day, mealTimestamp__month=meal_date.month, mealTimestamp__year=meal_date.year ) serializer = self.get_serializer(meals_by_date, many=True) return Response(serializer.data, status=status.HTTP_200_OK) That Code works on call it like this: http://localhost:8000/meals/by_date/ My problem is how can I enrich the method to gets data back with date parameter. For example with this call: http://localhost:8000/meals/by_date/2022-03-16T21:30:45.290Z/ -
Django CBV use Values from Modelform to Calculate other Model Fields
I am trying to make a warehouse management system with Django 3.2 based on this models: class itemtype(models.Model): item_id = models.IntegerField(primary_key=True) item_name = models.CharField(max_length=100) group_name = models.CharField(max_length=100) category_name = models.CharField(max_length=100) mass = models.FloatField() volume = models.FloatField() used_in_storage = models.BooleanField(default=False, null=True) class Meta: indexes = [ models.Index(fields=['item_id']) ] def __str__(self): return '{}, {}'.format(self.item_id, self.item_name) class material_storage(models.Model): storage_id = models.AutoField(primary_key=True) material = models.ForeignKey(itemtype, on_delete=models.PROTECT) amount_total = models.IntegerField(null=True) price_avg = models.FloatField(null=True) order_amount = models.IntegerField(null=True) order_price = models.IntegerField(null=True) timestamp = models.DateTimeField(default=timezone.now) def __str__(self): return '{}, {} avg.: {} ISK'.format(self.material, self.amount, self.price) "itemtype" defines basically the possible objects which could be stored and "material_storage" shows what is in stock. I tried to combine the total amount of every item as well as the average price paid for it and the amount and price for a single order in the same database row. The idea is to get the last record for the chosen item/material when a new order happens, add the amount of that order and recalculate the avg price. Theoretically this could be split up on two tables, but I don't see a reason to do so at the moment. However, I am not able to figure out the actual function code to do … -
system design for blockchain transactions ETL
I am trying to come up with scalable system design for one the projects i am working on in which i am using one of the google's blockchain public datasets bigquery-public-data.bitcoin_blockchain.transactions I would like to get the input/output address with most number of transactions by inflow and outflow and serve that information via a web application, so any time a GET request is sent for instance GET /address, my web app should get the top N input and output address for the given address and should return the response in the below format the Get request takes in address as a required parameter and startdate, enddate, flowtype(inflow,outflow, both) as optional parameters • { • "data": [ • { • "address": "", • "inflow_val": "", • "outflow_Val": "", • "total_val": "" • } • ], • "success": true • } I thought about exporting the transactions data from bigquery and dumping it to google cloud storage and have an airflow task that will copy over the bigquery extract from cloud storage to Postgresql, then i will setup django with postgresql as backend, and take care of GET request routes inside urls.py and the logic to calculate inflow and outflow inside of … -
return the user to specific blog post they deleted their comment from django
I am wondering could someone help me. I am new to Django and a part of my website the authorsied user will be allowed to comment on blogs that I have created. As part of this I want the user to be able to delete their own comment. Once they have chosen to delete their comment, I want them to be brought back to the blog that they originally had their comment on. As of now I have managed to get things working right up until the user is asked "are you sure you want to delete your comment", and this is when I run into errors. Just from reading and looking on the internet I think I need a "get_success_url" but this is where I get lost as I am not sure where to go from here or how to right the code. All I have in the class in my views.py file to render the html template. Thanks for any help provided :) -
Django filterset on aggregation, with multiple lookup expressions
For an API, I am calculating some values in real time (simple aggregations/functions such as sum, count, ratio). I would like to filter by these values with different operators. Currently for the filters i am using a filterset_class. The class looks a little like this: class BuildingFilter(filters.FilterSet): class Meta: model = Building fields = { "unit_number": ["gte", "gt", "lt", "lte", "range", "exact"], } address = filters.CharFilter(field_name="address", lookup_expr='icontains') The model Building has a relation with the model BuildingLeaseLog. In the BuildingLeaseLog there is a field rent. In the API response, I am returning a key "building_average_rent", which is calculated with an annotation in the queryset. So, for the field building_average_rent (and other similar ones), I would like to implement in this class filters with the following operators: "gte", "gt", "lt", "lte", "range", "exact". The API might receive any of the combinations of building_average_rent and the operators (ex building_average_rent__gte, building_average_rent__lt etc), and the filterset class should be able to filter accordingly However, I cannot: include it directly in the fields list (like I did with unit_number), because it is not an actual field of the model call a filter like I did for address, because I need 7 filters for it (one … -
How to insert bulk insert data in Djnago model Without providing fields
How to bulk insert data with only providing dictionary key and not worry about manually providing fields and type of fields in models.py What I have to do right now: models.py from django.db import models # Create your models here. class Info(models.Model): name = models.CharField(max_length=70) email = models.CharField(max_length=70) mongodb collection name | email Jon | j@g.com what I want without using fields and assigning more than 20-30 fields: name | email | fname | lname | cellNum | add | age | height | etc... for example using mongoClient to bulk insert data without providing fields data = {x:x, y:y, z:z} collection.insert_one(data) collection.insert_many([data,...]) -
How to prevent redirect_to_login from targeting LOGIN_REDIRECT_URL
So in general when a user logs in, my app redirects him to dashboard-overview: # settings.py # Login and Logout target routes LOGIN_URL = 'login' LOGIN_REDIRECT_URL = 'dashboard-overview' LOGOUT_REDIRECT_URL = '/' However for a specific case I want the user to be redirected to 'calculator-page' using a helper function which doesn't work as the user is again redirected to the value of LOGIN_REDIRECT_URL. # views.py def render_calculator(request, slug): """ Renders the calculator page """ # Check for the user being authenticated if not request.user.is_authenticated: return redirect_to_login('calculator-page') # routes to http://127.0.0.1:8000/login/?next=calculator-page which looks fine, # but then it fails after login to re-route as specified and sends to # 'dashboard-overview' again else: club_obj = Offer.objects.get(club__slug=slug) # Create Context context = { 'club_obj': club_obj, } return render(request, 'core/calculator.html', context) -
How to hide or modify <pk> in url in Django app?
In my url.py I have: path('gpd/<pk>/', views.gpd, name='gpd'), my view.py looks like: @login_required(login_url='login') def gpd(request,pk): # do smth context = {.... , 'pk':pk, } return render(request, 'app/gpd/gpd_form.html', context) I have noticed, that when my logined user change manually pk - then he has an access to page with another pk. How to prevent it? -
How do I get all objects that are more than a day old in Django?
I'm trying to write a query in Django for posts older than 24 hours. The Post form contains a DateTime field named Created_at and this field contains the time the post was added. How do I get all posts older than 24 hours in Django? -
the contact form dont send me it is show 404
I am a beginner in django and I have had a problem for 1 week now, several tutorials that I have watched have not solved anything, so I trust you. it's just making the different contact forms of my website designed with django work I therefore attach the source code of my project and the code, when I launch the send button (submit) I receive a 404 error DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' DEFAULT_FORM_EMAIL="ouesergegedeon225@gmail.com" EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = 'ouesergegedeon225@gmail.com' EMAIL_HOST_PASSWORD = 'Gedeon225@@' EMAIL_USE_TLS = 'True' EMAIL_USE_SSL = 'False' def send_mail(request): if request.method=="POST": name = request.POST.get['name'] subject = request.POST.get['subject'] email = request.POST.get['email_address'] message = request.POST.get['message'] send_mail( name, subject, email, message, 'ouesergegedeon225@mail.com', ['gedeonachat@mail.com'], fail_silently=False, ) message.info (request, 'Votre message a été envoyé') return render(request, 'contact.html') path('send_mail/', views.send_mail, name="send_mail"),``` -
Is there a way to change netflix password every one hour or daily automatically?
i am working on a project lately . i want to change netflix or any other OTT platform on a hourly or daily basis. Is there a way to do it? -
How can I add the next 1st of August as DateTimeField default value in Django?
I have the following model and want to add the next August (midnight time) from now as a default value for offer_start: class Offer(models.Model): """ A table to store all available offers for an upcoming season """ club = models.ForeignKey(Club, on_delete=models.CASCADE, related_name='offer') season_start = models.CharField(max_length=40) seasons_duration = models.IntegerField() offer_start = models.DateTimeField(auto_now_add=False, default= ???) roi_goal = models.FloatField() roi_point = models.FloatField() def __str__(self): return f'Offer by {self.club} for season {self.season_start}' Is there any way to make such a specification? -
form won't be submitted when i used select fields on the template (dependent on each other) using Django
I have noticed that my form don't want to be submitted because of 2 field that depends on each other(dependend dropdown list, where I have made the "pid" field value(exit in the 2 models) as a common point between the 2 fields), after click on the button the values that i have choose them as a user disappear automatically when i click on the button and in same way the form don't want to be submitted: those are the 2 fields ow i have called them on the html template: Here is the code <select id="select1"> <option selected disabled="true"></option> {% for categories in categoryobj%} <option value="{{categories.pid}}">{{categories.name}}</option> {% endfor%} </select> <select id="select2"> <option selected disabled="true"></option> {% for items_size in sizeobj%} <option value="{{items_size.pid}}">{{items_size.name}}</option> {% endfor%} </select> Js <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function(){ var $select1=$('#select1'), $select2=$('#select2'), $options = $select2.find('option'); $select1.on('change',function() { $select2.html($options.filter('[value="'+this.value+'"]')); }).trigger('change'); }); </script> with the button of submitting: <button class="floated" onclick="location.href='#results'" type="submit">Submit</button> Ps: if i change those two fields to tag : the code html: <p >{{form.profile_family}} </p> <p >{{form.profile_size}} </p> -----> the form is submitting ----> But i don't want that exactly , i want a dependent dropdown list Any help will be appreciated please, thanks. -
WinError 10061 No connection could be made because the target machine actively refused it - Django Python Error when Sending Email
I'm just learning Django and wasn't able to figure this out. I'm trying to make my Django App send emails. But keep encountering this error on Submitting. Error Image I've turned the Allow less secure apps option ON in Gmail Settings, & have tried adding EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' to the settings.py but it prints the emails in the console instead of actually sending them, which doesn't server the purpose Settings.py """ Django settings for expenseswebsite project. Generated by 'django-admin startproject' using Django 4.0.3. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path import os from django.forms import EmailField import django_heroku from django.contrib import messages from dotenv import load_dotenv load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-*akbxcj*md2z0&#vai@lw816t6p#te!fdo^#4j194^x7r7p-zo' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'expenses' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
SSLError. SSL certificate verification failed in beautifulsoup4
this is a part where I search for things on the internet. I am using beautifulsoup4 for web search and scraping them. but it is giving SSL error Here is my code def searchBing(query, num): url = 'https://www.bing.com/search?q=' + query print(url) urls = [] page = requests.get(url, headers= {'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36', "Accept-Encoding": "*", "Connection": "keep-alive" }) soup = bs(page.text, 'html.parser') for link in soup.find_all('a'): url = str(link.get('href')) if url.startswith('http'): if not url.startswith('http://go.m') and not url.startswith('https://go.m'): urls.append(url) return urls[:num] # Extraxt text from the internet (from similar website) def extractText(url): page = requests.get(url, headers={'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36', "Accept-Encoding": "*", "Connection": "keep-alive" }) soup = bs(page.text, 'html.parser') return soup.get_text() Traceback of the error -
Cookies disappear after reload the page
response.set_cookie(key=SIMPLE_JWT.get('REFRESH_AUTH_COOKIE'), value=response.data.get('refresh'), expires=datetime.now()+SIMPLE_JWT.get('REFRESH_TOKEN_LIFETIME'), samesite='None', secure=SIMPLE_JWT.get('AUTH_COOKIE_SECURE'), httponly=SIMPLE_JWT.get('AUTH_COOKIE_HTTP_ONLY')) I'am using Django Rest Framework to set the JWT Refresh cookie, until this point everything is ok, but when I reload the page the cookie just disappear so I can't retrieve the value any more by JS, but when I send a new request the cookie appears in the Django log. So, I don't know what is happening because the cookie is set in the browser, but in a way that I can't retrieve -
Carousel Bootstrap don't work with data database
Carousel shows the data from the database but the slider does not work and the cards are duplicated. I have tried to add the loop inside the cards or the carousel item itself but it does not work. the slider arrows are not visible because they are on a white background This is my code: <div id="carouselExampleControls" class="carousel slide" data-ride="carousel" data-interval="false"> <div class="carousel-inner"> {% for i in usuarios%} <div class="carousel-item active"> <div class="card mb-3"> <div class="card-body"> <div class="row justify-content-center"> <div class="col-sm-8 align-self-center border-sm-right border-md-right border-xl-right border-lg-right"> <div class="card-body"> <!--<h5 class="card-title">Card title 1</h5> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>--> <img src="../../static/ejemploMates/JoseJuan.png" class="img-fluid float-left"> <div class="infoPersonal"> <p>{{i.usuario.username}}</p> <p class="edad">38 años</p> <p class="genero">Género: {{i.genero}}</p> </div> <p class="text-center">A 700 metros de ti y acercándose.</p> </div> </div> <hr class="sm"> <div class="col-sm-4 align-self-center"> <div class="card-body"> <h5 class="card-title">Con piso</h5> <img src="../../static/ejemploMates/fotosPiso.png" class="img-fluid float-left"> <img src="../../static/ejemploMates/Home-Logo-Transparent-File.png" class="img-fluid float-right"> </div> </div> </div> </div> <hr> <div class="card-body"> <div class="row justify-content-center special-card"> <div class="col-sm-8 align-self-center"> <div class="card-body"> <p class="card-text text-center">Soy José Juan y me interesan tus órganos. Vente a compartir piso conmigo.</p> </div> </div> <div class="col-sm-4 … -
Django channels self.send() from custom function
Is it possible to self.send() from custom function inside consumer.py? I have a roulette game which runs inside a loop after every 30 seconds. Inside that loop I call a function to save the winning game details and update the user model with their winnings. I would like to also send that to the front end view so the user does not need to refresh the page to update their balance. The problem currently is that the way I thought to do it is not working as the self.send() inside my custom save_roll() function is not working. How can something like this be achieved? consumers.py @database_sync_to_async def save_roll(self, result, roll_color, round_number): winners = Bets.objects.filter(round_number=round_number, bet_choice=roll_color) multiplier = 0 if roll_color == 'blue' or roll_color == 'red': multiplier = 2 elif roll_color == 'green': multiplier = 14 for winner in winners: winnerId = winner.id winnerBet = winner.bet_value userObj = CustomUser.objects.filter(id=winnerId)[0] newBalance = userObj.user_coins + (winnerBet * multiplier) CustomUser.objects.filter(id=winnerId).update(user_coins=newBalance) self.send(text_data = json.dumps({ 'balance': newBalance })) Roulette.objects.create(win = result, roll_color = roll_color, round_number = round_number, is_over = True) class RouletteGame(AsyncWebsocketConsumer): async def connect(self): self.connected = True await self.accept() while self.connected: await asyncio.sleep(30) server_seed = get_random_string(length=64) public_seed = random.randint(0, 999999) round = await get_round() … -
How do I iterate inside a queryset in django template
My django view returns a dictionary people with values for all keys in list format. The code for the view is: class ProjectDetail(View): def get(self, request, pk, *args, **kwargs): project = Project.objects.get(pk=pk) roles = Role.objects.filter(project=pk) people = {} for role in roles: try: people[role] += Person.objects.filter(role=role.pk) except KeyError: people[role] = [Person.objects.filter(role=role.pk)] context = { 'project': project, 'people': people } return render(request, 'project_management/project_detail.html', context) In order to iterate through the dictionary I used: {% for designation, persons in people.items %} <h5> {{ designation.role_name }} </h5> <ul> {% for person in persons %} <!-- My Problem lies here, this loop is not iterating, it's running only once--> <li> {{person}} </li> {% endfor %} </ul> {% endfor %} The result I got is: I want the items inside queryset listed out separately, instead of being shown inside square brackets. How can I make that happen? -
Joining two tables and search/filter within serialized data with django-rest-framework
I am joining two tables than I would like to do keyword searching. I need to create a single SQL and add a WHERE with argument(s). I am using django-rest-framework. models.py from django.db import models class Paper(models.Model): title = models.TextField() paper_lan = models.CharField(max_length=2) nb_authors = models.SmallIntegerField() class Meta: managed = False def __str__(self): return str(self.title) class Abstract(models.Model): paper = models.OneToOneField(Paper, related_name='abstracts', on_delete=models.CASCADE, primary_key=True) abstract = models.TextField() class Meta: managed = False def __str__(self): return str(self.abstract) serializers.py from rest_framework import serializers from .models import Paper, Abstract class PaperAbstractSerializer(serializers.ModelSerializer): class Meta: model = Paper #fields = '__all__' fields = ['title', 'paper_lan', 'nb_authors', 'abstracts'] depth = 1 class PaperSerializer(serializers.ModelSerializer): class Meta: model = Paper fields = ('title', 'paper_lan', 'nb_authors') class AbstractSerializer(serializers.ModelSerializer): class Meta: model = Abstract fields = ['abstract'] filters.py from django.db.models import Q from django_filters.rest_framework import CharFilter, FilterSet from .models import Paper, Abstract class PaperAbstractFilterSet(FilterSet): query = CharFilter(method='qfilter') class Meta: model = Paper fields = ['query'] def qfilter(self, queryset, name, value): squery = Q(abstracts__icontains=value) return queryset.filter(squery) class PaperFilterSet(FilterSet): query = CharFilter(method='qfilter') class Meta: model = Paper fields = ['query'] def qfilter(self, queryset, name, value): squery = Q(title__icontains=value) return queryset.filter(squery) class AbstractFilterSet(FilterSet): query = CharFilter(method='qfilter') class Meta: model = Abstract fields = ['query'] … -
Auto refresh HTML database data in Django - Ajax?
I have a Django server which is locally hosted and displays sensor data from a MySQL database. This data is displayed on the instruments.html page through variables such as {{qs.value}} which comes from the views.py, models.py and URLs.py. The views.py page is as follows: from django.http import HttpResponse from django.shortcuts import redirect, render from .models import Sensorresult def db(request): qs = Sensorresult.objects.using('Vision').get(sensorresult='1') return render(request, 'authenticate/instruments.html',{'qs':qs}) The problem I have is that I want the database information to update on the html every second, whereas currently it only updates when the page is refreshed. I know I could place a line of javascript at the top of the page and have the entire webpage constantly update, but I only want the database values to update. Does anyone have any suggestions as to how to do this? From googling have come across Ajax, however this is something I have no experience in and I am unsure how my code would be edited to accommodate this? Many thanks -
Django Conditional ORM Query
I am creating a Blog website where for each blog a user can like or dislike the post. Now every time user goes on Index page I want to change the like button i.e if user has liked the post then a dislike button otherwise like button. For this I need to get the variable IsLiked from the views.py file. This is the Query that I have written. posts = Post.objects.exclude(users=request.user).select_related('user__people','ProductAvailability').prefetch_related('images_set').annotate(comments_Count = Count('comments_post',distinct=True)).annotate(Count('Likes',distinct=True)).all().order_by('-id') for post in posts: if(post.Likes.filter(id=user_id).exists()): isLiked = True else: isLiked = False Here the problem is that for every post there is a separate query sent to DB. This is my Blog Post Model -> class Post(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) # category = models.ForeignKey(Category, on_delete=models.PROTECT) ProductAvailability = models.ForeignKey(ProductAvailability, on_delete=models.PROTECT, null=True, blank=True) title = models.CharField(max_length=255,null=True) description = models.CharField(max_length=1000,null=True) Likes = models.ManyToManyField(to=User, related_name='Post_likes') favourites = models.ManyToManyField(to=User,blank=True,related_name="favourite") Tag1 = models.CharField(max_length=255,null=True,blank=True) Tag2 = models.CharField(max_length=255,null=True,blank=True) Tag3 = models.CharField(max_length = 255, null = True, blank = True) Tag1_Name = models.CharField(max_length=255,null=True,blank=True) Tag2_Name = models.CharField(max_length=255,null=True,blank=True) Tag3_Name = models.CharField(max_length=255,null=True,blank=True) users = models.ManyToManyField(User, related_name='users_hidden_from_post') Created_date = models.DateTimeField(auto_now_add=True) Updated_date = models.DateTimeField(auto_now=True) PS: Please Ignore the redundant Info in the Post Model I want to send the User id with the Query and check if individual post is … -
django way to get and save a tree of folders and files
When I came across a project to save a tree of files - means including subdirectories and files, not just files - I couldn't find an appropriate solution for the problems. note: This question is not the same as this. They speak of two different things, mine: How to save, his/hers: How to show - a tree of files I do not want to write the code purely by myself or use a library that isn't suggested by Django. To understand better, let me say a user will upload these three files: src/statistics test/tests img/9744t3vo5.png though files can be placed in root or home or any other place in the file system (let me say simpler: files path should be relative) But the problem is how to get & save files in that manner (with relative path took effect) not the issue to show files that is solved in the question linked above -
display the selected posts of an authorized user
how to get the selected tasks of an authorized user correctly now class Task(models.Model): user_info = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, name='userInfo') title = models.CharField(max_length=100) text = models.TextField(max_length=10000) class Favourite(models.Model): task_id = models.ForeignKey(Task, on_delete=models.CASCADE, blank=True, null=True, related_name='favourites',name='taskId') user_info = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, name='userInfo') views.py class FavouriteUserView(generics.ListAPIView): serializer_class = FavouriteReceivingSerializer pagination_class = MyCursorPagination permission_classes = [IsAuthor] def get_queryset(self): return Favourite.objects.filter(userInfo=self.request.user) urls.py path('user/<int:pk>/favourites/', FavouriteUserView.as_view()), how to get favorite posts without sending int:id without int:id "detail": "Not found." -
How can I return several aggregates based on a condition within a queryset?
So I have the following model which contains different booleans and one amount field. I now want to render the overall sum amount for each boolean when true (only one boolean will be true at once always). class UserTransaction(models.Model): """ A table to store transactions between a user and Farena """ user = models.ForeignKey(User, on_delete=models.CASCADE) offer = models.ForeignKey(Offer, on_delete=models.CASCADE, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) amount = models.FloatField() is_deposit = models.BooleanField(default=False) is_withdrawal = models.BooleanField(default=False) is_interest = models.BooleanField(default=False) is_investment = models.BooleanField(default=False) is_return = models.BooleanField(default=False) def __str__(self): return f'{self.user.first_name} {self.user.last_name} transacted {self.amount}' I tried to build it with annotate but that would add fields for each instance which wouldn't solve my issue as far as I understand it. Additionally using aggregate I couldn't implement a condition and also wouldn't know how to access the aggregated value in the template?