Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to saving multiple forms also has cloned forms in django?
views.py @login_required def add_product(request): productform = ProductForm() variantsform = VariantsForm() productvariantsform = ProductVariantsForm() if request.method == 'POST': productform = ProductForm(request.POST, request.FILES) variantsform = VariantsForm(request.POST, request.FILES) productvariantsform = ProductVariantsForm(request.POST, request.FILES) if productform.is_valid(): product = productform.save(commit=False) vendor = CustomUser.objects.filter(id=request.user.id) print(vendor) product.vendor = vendor[0] product.slug = slugify(product.product_name) product.save() if variantsform.is_valid(): variantsform.save() #finally save if productvariantsform.is_valid(): productvariantsform.save() #finally save return redirect('vendor:vendor-admin') else: return HttpResponse("Nothing submitted...") else: productform = ProductForm variantsform = VariantsForm() productvariantsform = ProductVariantsForm() return render(request, 'vendor/add_product.html', {'productform': productform, 'variantsform':variantsform, 'productvariantsform': productvariantsform}) add_product.html <div class="container mt-5" id="p"> <h1 class="title">Add Product</h1> <div class="card" style="width: 38rem;"> <form method="POST" action="{% url 'vendor:add-product' %}" enctype="multipart/form-data"> {% csrf_token %} <div class="row"> <div class="col-lg-12 col-md-12"> {{ productform.vendorid|as_crispy_field }} </div> <div class="col-lg-12 col-md-12"> <a id="vendor_id_search" class="btn btn-info mt-4">search</a> </div> </div> <div id="show_vendorname"> </div><br> {{ productform.maincategory|as_crispy_field }} {{ productform.productcategory|as_crispy_field }} {{ productform.subcategory|as_crispy_field }} {{ productform.product_name|as_crispy_field }} {{ productform.brand_name |as_crispy_field }} <br> <div> <p></p> </div> <hr> <div id="order-details-booking"> <div class="row"> <div class="form-holder"> <div class="col"> <h1>Variant Form</h1> {{ variantsform.variant_type|as_crispy_field}} {{ variantsform.variant_value|as_crispy_field}} {{ productvariantsform.price|as_crispy_field}} {{ productvariantsform.initial_stock|as_crispy_field}} {{ productvariantsform.weight_of_product|as_crispy_field}} <div class="input-group mb-3"> <label class="input-group-text" for="upload_file">Upload Images</label> <input type="file" id="upload_file" onchange="preview_image();" multiple class="form-control"> </div> <div id="image_preview"></div> {% comment %} {{ productvariantsform.images|as_crispy_field}} {% endcomment %} {{ variantsform.sleeve|as_crispy_field }} {{ variantsform.material|as_crispy_field }} {{ variantsform.neck|as_crispy_field }} <div class="col s1"> … -
how to use local host server for domain django
my problem seems to be a funny one...... i'm developing a django ecommerce app. the problem is that when the link for activation of a user account is sent on the console, instead of getting my local server as an domain e.g http://127.0.0.1:8000/account/activate/OQ/awzscp-c1075f82b127ff18fb676523a9a02d71)/ i get http:// example.com /account/activate/OQ/awzscp-c1075f82b127ff18fb676523a9a02d71)/ instead -
Adding settings to settings.py - Django
I'm following this Django Tutorial to add photos to my Django webpage. It says to put the following codes into my settings.py. However, I'm sort of confused because I know the two "span class" lines are definitely not Python codes. Therefore, does anyone know what I should do? Do I just include the two Python codes instead? span class="hljs-comment"> # Base url to serve media files</span> MEDIA_URL = <span class="hljs-string">'/media/'</span> <span class="hljs-comment"> # Path where media is stored</span> MEDIA_ROOT = os.path.join(BASE_DIR, <span class="hljs-string">'media/'</span>) Thanks in advancd! -
Password not hashing while using Django Rest Framework and Custom User Modelh
Problem: I needed a backend for authenticating with phone number and I decided to make it in Django. I am using Django Rest Framework for API and Custom User Model. When I create a user using Django Admin, the password is hashed and I can log in using the login API I created. But when I create a user using API ( created using DRF ) the password is not hashed due to which I am not able to log in. Note: I am using KNOX authentication for token authentication but that is working fine and I do not think that that is the problem Project Structure ( only files that are needed are included ): server\ accounts\ admin.py forms.py models.py serializers.py urls.py views.py server\ settings.py urls.py manage.py Code: # settings.py """ Django settings for server project. Generated by 'django-admin startproject' using Django 3.2.9. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from datetime import timedelta from pathlib import Path # 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/3.2/howto/deployment/checklist/ # SECURITY WARNING: … -
502 occurs when creating environment on elastic beanstalk
I'm having an issue deploying my first Django project. Here's my config.yml: global: application_name: testapp branch: null default_ec2_keyname: aws-eb default_platform: Python 3.8 running on 64bit Amazon Linux 2 default_region: us-west-2 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: eb-cli repository: null sc: null workspace_type: Application And here's my django.config: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: djangoproject.wsgi:application I have followed this doc. But after I did eb create testapp-env, I get 502 error: image of the error I will provide further information if you need. Thank you in advance for your help. -
HTML audio tag play button is greyed out on Django project
For some reason the play button is greyed out on my Django website. I used this same exact HTML code in a blank HTML document and it worked as it should, so I don't think there's a problem finding the file, or a syntax error. While running the server locally I am not seeing any errors in the command line either. How it looks on blank HTML file How it looks on website Code: <audio src="C:\Users\zach2\music\download.mp3" controls> </audio> Is there something that I need to change in one of the Django files to enable audio to work properly? I am very new to Django and Web development so please forgive my ignorance. If you want to see another file please let me know and I will update the post ASAP. Thank you. -
Save Temporary Data in Django
Is there any way to save temporary data in django framework? For example I need to save temp notices in a table, with expiration date. To give a better example, I have a table called product and in this table there are several fields such as: title, description, notices and others... is it possible to create a product with a temporary notice? like, this product has this notice until tomorrow. -
Question about the location of the git repository when deploying Django project on Elastic Beanstalk
i'm new in both python and elastic beanstalk. Here's my file structure: /.git # <- here's my git repo /my-first-django |-- django-project |-- app |-- django-project | |-- __init__.py | |-- settings.py | |-- urls.py | `-- wsgi.py `-- manage.py /venv When I read this doc, I can see they create git repository at the same level as django-project. Should I move the repository? Or am I fine with my current structure when deploying with awsebcli? Thank you for your help! -
Need Serialize a custom filed AVG notes for my API in Django
models.py from django.db import models from django.db.models import Avg from users.models import UserProfile from subjects.models import Subject class Note(models.Model): id_user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='user_note') id_subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='subject_note') exam_note = models.IntegerField() @property def average_note(self): if hasattr(self, '_average_note'): return self._average_note return Note.objects.aggregate(Avg('exam_note')) Thats my Note models and i need to calculate the notes average to serialize it and send in request resonse views.py class AvgNoteViewSet(viewsets.ModelViewSet): serializer_class = AvgSerializer authentication_classes = (TokenAuthentication,) permission_classes = (NotePermissions,) def get_queryset(self): return Note.objects.all().annotate(_average_note=Avg('exam_note')) And that is my get_queryset redefined method to calculate de average notes, but im just having a list of notes for result of that query, like that: resques response serializers.py class AvgSerializer(serializers.ModelSerializer): """ Serializes a notes AVG """ average_note = serializers.SerializerMethodField() def get_average_note(self, obj): return obj.average_note class Meta: model = Note fields = ['average_note'] And this is my serializer My intencion is try to get an avergate from the exam_notes from the logged user, so i understand that i need to try to group by user_id ant then agregate the average. This is my postgresql table from when im querying: notes_table I based my code from How to calculate average of some field in Django models and send it to rest API?, … -
Django database information doesn't exist when deployed to Heroku
I recently deployed a django rest api to heroku and the database is not working properly. When trying to log in, it seems that the user object that was in my sqlite database in my own files does not exist and therefore it tells me that my credentials are invalid. Does anyone know how to make it so that the database data gets uploaded to Heroku? Here is my Procfile: release: python manage.py makemigrations --no-input release: python manage.py migrate --no-input web: gunicorn rrt.wsgi Here are my Django settings: 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', 'api', 'articles', 'author_auth', 'authors', 'threads', 'category', 'rest_framework', 'corsheaders', 'rest_framework_simplejwt.token_blacklist', 'ckeditor', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware' ] ROOT_URLCONF = 'rrt.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'rrt.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # … -
how to change images in boostrap's example?
I am a rookie of html. My English is also poor. Just download the bootstrap-v4 examples. One of the examples is carousel, but i don't kown which place in codes to change the images. And I don't understander the meaning of code below. Who can help me would be much appreciated. example's link :https://v4.bootcss.com/docs/examples/ .bd-placeholder-img { font-size: 1.125rem; text-anchor: middle; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } @media (min-width: 768px) { .bd-placeholder-img-lg { font-size: 3.5rem; } } </style>``` -
Django how to show many2many extra fields in a form?
here are my models.py: class EssentialOil(models.Model): name = models.fields.CharField(max_length=120, verbose_name="Nom") latin_name = models.fields.CharField(max_length=120, verbose_name="Nom latin") abbreviation = models.fields.CharField(max_length=8, verbose_name="Abbréviation") image = models.fields.CharField(default=None, null=True, blank=True, max_length=255, verbose_name="Photo") administrationmodes = models.ManyToManyField('AdministrationMode', through="EssentialOil_AdministrationMode", verbose_name="Mode d'administration") components = models.ManyToManyField('Component', through="EssentialOil_AdministrationMode", verbose_name="Composants") warnings = models.ManyToManyField('warning', through="EssentialOil_AdministrationMode", verbose_name="Points d'attention") properties = models.ManyToManyField('property', through="EssentialOil_AdministrationMode", verbose_name="Propriétés") uses = models.ManyToManyField('use', through="EssentialOil_AdministrationMode", verbose_name="Utilisations thérapeuthiques") class Meta: ordering = ['name'] def __str__(self): return self.name class AdministrationMode(models.Model): mode = models.fields.CharField(max_length=100, verbose_name="Mode") description = models.fields.CharField(max_length=2000, verbose_name="Description") warning = models.fields.TextField(max_length=2000, default="Aucun", verbose_name="Point d'attention") eo = models.ManyToManyField(EssentialOil, through='EssentialOil_AdministrationMode', blank=True, verbose_name="H.E. concernées") class Meta: ordering = ['mode'] def __str__(self): return self.mode class EssentialOil_AdministrationMode(models.Model): class Efficiency(models.IntegerChoices): RARE = 1 PARFOIS = 2 SOUVENT = 3 IDEAL = 4 eo = models.ForeignKey("EssentialOil", null=True, on_delete=models.CASCADE) am = models.ForeignKey("AdministrationMode", null=True, on_delete=models.CASCADE) co = models.ForeignKey("Component", null=True, on_delete=models.CASCADE) pr = models.ForeignKey("Property", null=True, on_delete=models.CASCADE) us = models.ForeignKey("Use", null=True, on_delete=models.CASCADE) wa = models.ForeignKey("Warning", null=True, on_delete=models.CASCADE) efficiency = models.IntegerField(Efficiency.choices) class Meta: unique_together = [['eo', 'am']] My forms.py: from django import forms from django.forms import ModelForm from .models import EssentialOil, AdministrationMode, Component, Warning, Property, Use class CreateEssentialOil(ModelForm): class Meta: model = EssentialOil fields = "__all__" administrationmodes = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=AdministrationMode.objects.all(), label="Mode d'administration") components = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Component.objects.all(), label="Composants") warnings = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Warning.objects.all(), label="Points d'attention") properties = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Property.objects.all(), … -
update_create is creating new feilds instead of updating total
payments = list((expense .annotate(month=Month('startDate')) .values('month') .annotate(total=Sum('cost')) .order_by('month'))) for i in payments: paymentMonths = (i["month"]) paymentTotal= (i["total"]) obj, created = Payment.objects.update_or_create( author=curruser, date=paymentMonths, total = paymentTotal, defaults={"total": paymentTotal}, ) totalcost = Payment.objects.filter(author = curruser.id) Apparently, it should update the (date = 12) total but it is making new ones with the updated value, it might be because the totaldate is diff or maybe I'm wrong it is confusing -
Django, url not found 404
Project Folder structure I am new to django. I am trying to create a simple rest api end point, but I get a 404. I am sure I am missing some setting. models.py class DisplayItems(models.Model): yesNo = models.CharField(max_length=10) yogaMessage = models.CharField(max_length=50) yogaTimeMessage = models.CharField(max_length=100) @classmethod def create(cls, yesNo, yogaMessage, yogaTimeMessage): displayItems = cls(yesNo=yesNo, yogaMessage=yogaMessage, yogaTimeMessage=yogaTimeMessage) return displayItems serializers.py from .models import DisplayItems class DisplayItemsSerializer(serializers.ModelSerializer): yesNo = serializers.CharField(max_length=10) yogaMessage = serializers.CharField(max_length=50) yogaTimeMessage = serializers.CharField(max_length=100) class Meta: model = DisplayItems fields = ('__all__') urls.py from .views import DisplayItemsViews from django.contrib import admin urlpatterns = [ path(r'^admin/', admin.site.urls), path(r'^zzz/', DisplayItemsViews.as_view()), ] views.py from rest_framework.response import Response from rest_framework import status from .serializers import DisplayItemsSerializer from .models import DisplayItems class DisplayItemsViews(APIView): def get(self, request): displayItems = DisplayItems.create("YES!", "There's yoga today", "At 2:00 pm Eastern Time") serializer = DisplayItemsSerializer(displayItems) return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) The url I am trying to run is http://127.0.0.1:8000/zzz/ I have read almost all relevant stackoverflow posts, but can't seem to understand what I am missing. -
Get the users download directory
I'm on my linux server and I want to save something into the downloads folder from the user which is using the website, how do I get the downloads path from the user, when I try to save something in the downloads folder a folder named "downloads" gets created in my root directory, and not in my computers downloads folder. -
How to update user as an admin in djoser django?
My problem is that I want to change user status from admin panel. Admin should be able to change field "is_staff" from his panel. When I read the documentation, it says: User Use this endpoint to retrieve/update the authenticated user. Default URL: /users/me/ https://djoser.readthedocs.io/en/latest/base_endpoints.html#user Okay, and I am planning to use it to change user's password later, but it makes sense to change users password while being logged in as this user. But how to change another field ('is_staff') in another user while being logged in as admin? Does sending request to /users/me/ make sense? I will update this with any code needed. -
Creating endpoint fetch data from local json file using django rest
I am trying to create django application with a REST api endpoint. The application should be able to able to fetch a list of users from the json file The API should also allow the user to fetch a specific user from the json file. Json file {users:[ {"name":"Julia", "phone" :'+111454545' }, {"name":"Kenny" "phone":"+9911111111' }, ]} How do I do that ? -
reference a HTML tag with javascript that was generated from django json schema
i am trying to reference a HTML tag that is generated by a django's django_jsonforms link JSON Schema link via javascript to dynamically update the form. For example 2 dropdowns in a form, if you make a selection in the 1st dropdown the 2nd dropdown should update. I've done this for HTML selection tags that i manually typed out but i am trying to get this to work for HTML generated by JSON Schemas. Here is what i've tried: inspect HTML page and try to call the tag by name with var project_selection = document.getElementsByClassName("form[project]")[0]; this didnt work, which i was a little surprised by since i see when i inspect the page that the select tag has name="form[project]" then i thought maybe the JSON Schema renders the tag after the javascript runs so i tried adding defer into my <script defer> and that didnt work i tried using JSON Schema $id #anchor and $ref but none of those worked to reference the tag by ID I am sure someone has come across this before so i hope this is an easy answer. At the end of the day i know i need to use the following with the JSON … -
Django UUID Validation Error: Sometimes object, sometimes UUID
This page is supposed to show a post for a social media website. Within <div class="is-flex">, I have an if/else/endif block for showing a like/unlike button. As the code is right now, it successfully shows the like/unlike button on non-shared posts. I would like to have it so the like/unlike button appears on all posts as long as {user.is_authenticated} is true, but if I move the like/unlike code block anywhere else in the div, I get this error. Even adding the line for the button and commenting it out gives the error. No variables are being written, only read, so I don't know why Django would get the UUID in one instance and the entire post object in another instance. Lines with *NOTE* comments are lines I tried duplicating/moving the like/unlike code block to without success. {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} {% #header user=user %} {% /header %} {% load crispy_forms_tags %} {% load markdown_extras %} {% load url_check %} {% load comment_like %} {% load post_like %} <main> <div class="is-flex mt-3"> <small>Posted by: <a href="/author/{% valid_url_profile post.author.id %}">{{post.author.displayName}}</a></small> <small> &nbsp;• {% load tz %} {% localtime on %} <small>Created: {{post.published}}</small> … -
Show related item django
I have the following models: class Category(models.Model): name = models.CharField(max_length=255) class Element(models.Model): category = models.ForeignKey(Category) name = models.CharField(max_length=255) class Topic(models.Model): category = models.ForeignKey(Category) element = models.ForeignKey(Element) name = models.CharField(max_length=255) I basically need to add New topic in catégory id =1 and get only a list of élément belongs to category 1 I have created a view New topic in category id =1, but for fields element in form i get all elements for all categories -
how do I align RadioSelect button?
For some reason this button comes with weird alignment, I want it aligned next to gender label but the ul element comes with pre existing "margin-block-start, margin-block-end and padding-inline-start" so how do I align it right? html <div class="block"> <label>Gender</label> <span class="placer">{{ form.gender }}</span> </div> css #id_gender li { list-style-type: none; display: inline-block; } forms.py gender = forms.ChoiceField(choices=GENDER_CHOICES, widget=forms.RadioSelect(), required=True) I want the radios(Male and Female) to be aligned next to Gender. Thnx in advance! -
Fetch : authentication credentials were not provided
When I request this, everything is ok and I get the data: const get_players = async()=>{ const response = await fetch('http://127.0.0.1:8000/player_stats/api/players/') const data = await response.json() console.log(data) } But when I put permission_classes in views.py, I recive this in the console: {detail: 'Authentication credentials were not provided.} I am a beginner in Javascript so I wll hope you can understand. I dont know how to put the authentication credentials in my fech. Views.py class PlayersView(ModelViewSet): permission_classes = [IsAuthenticated] serializer_class = PlayersSerializer queryset = Players.objects.all() def list(self, request): queryset = Players.objects.all() serializer = PlayersSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = Players.objects.all() qs = get_object_or_404(queryset, pk=pk) serializer = PlayersSerializer(qs) return Response(serializer.data) Urls.py router = DefaultRouter() router.register('players',views.PlayersView,basename='players') app_name = 'main' urlpatterns = [ path('',include(router.urls)), ] Any idea? -
Constrain unique_together could have conflict with the unique_field in dajngo Class
Basically, I would like to know if there is any conflict using the constrain unique_together as well as the parameter unique=true in one of the fields that belong to the array of the unique_together. it´s because I can´t remove the parameter unique=true of my field because it´s used as a foreigner key in another model. class User(AbstractUser): # User information fiscal_number = models.CharField(max_length=30,unique=True) phone = models.CharField(max_length=15, null=True) email = models.EmailField(max_length=254, verbose_name='email address') class Meta: unique_together = ['fiscal_number', 'email'] As you can see the goal is to make the combination of the fields fiscal_number and email unique -
Why isn't Django Sitemap showing the URLs
I've been trying to make my django sitemaps work for a small blog application. After checking out multiple tutorials, I still can't get the sitemaps work properly. Here's my urls.py: from django.contrib import admin, sitemaps from django.urls import path from django.urls import include from rx import views from django.conf.urls.static import static from django.conf import settings from django.contrib.sitemaps.views import sitemap from rx.sitemaps import Static_Sitemap sitemaps = { 'static': Static_Sitemap, } urlpatterns = [ path('ckeditor/', include('ckeditor_uploader.urls')), path('admin/', admin.site.urls), path('', views.index, name='index'), path('blog/', views.blog, name='blog'), path('about/', views.about, name='about'), path('<slug:cat_slug_name>/', views.cat, name='cat'), path('<slug:cat_slug_name>/<slug:post_slug_name>/', views.blog_post, name='blog_post'), path('sitemap.xml/', sitemap, {'sitemaps': sitemaps}), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here's my settings.py: """ Django settings for rankxero project. Generated by 'django-admin startproject' using Django 3.2.9. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') MEDIA_DIR = os.path.join(BASE_DIR, 'media') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: don't run with debug turned on in production! … -
Django annotate queryset by predicate and count results
I have two models: class Game(models.Model): id = models.AutoField(primary_key=True) class Score(models.Model): id = models.AutoField(primary_key=True) game = models.ForeignKey(Game, related_name="score", on_delete=models.CASCADE) first_score = models.IntegerField(blank=True) second_score = models.IntegerField(blank=True) is_rusk = models.BooleanField(blank=True) And I got a queryset of Game objects: [ { "id": 314317035, "score": [ { "first_score": 5, "second_score": 1, "is_rusk": false } ] }, { "id": 311298177, "score": [ { "first_score": 5, "second_score": 2, "is_rusk": false } ] }, { "id": 310278749, "score": [ { "first_score": 5, "second_score": 2, "is_rusk": false } ] }, { "id": 309866238, "score": [ { "first_score": 5, "second_score": 0, "is_rusk": true } ] }, { "id": 307926664, "score": [ { "first_score": 5, "second_score": 0, "is_rusk": true } ] }, { "id": 306047964, "score": [ { "first_score": 4, "second_score": 5, "is_rusk": false } ] }, { "id": 304881611, "score": [ { "first_score": 5, "second_score": 3, "is_rusk": false } ] }, { "id": 304468136, "score": [ { "first_score": 5, "second_score": 2, "is_rusk": false } ] }, ] I want to annotate this queryset with rusks_cnt, it will be count of objects with is_rusk=True, If there is a way to not add this to every object, just as one field, that would be good too. I think easiest way to …