Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Slow installation of python packages in aws lightsail
I have been trying to install some python packages in lightsail but it has been slow mainly taking more than 8 hours thus far. I have used pip install -r mypiplistreq.txt after long hours I used pip3 install -r mypiplistreq.txt it was still the same result, the pip comes up with the messageS such as `INFO: pip is looking at multiple versions of urllib3/[PACKAGE_NAME] to determine which version is compatible with other requirements. This could take a while.` `INFO: This is taking longer than usual. You might need to provide the dependency resolver with stricter constraints to reduce runtime. If you want to abort this run, you can press Ctrl + C to do so. To improve how pip performs, tell us what happened here: https://pip.pypa.io/surveys/backtracking` And it then downloads different versions of .whl or tar.gz files some of them numbering over 15 versions with different file sizes in Kb and Mb There have been many such messages mostly for packages which I did not even specify in my requirements list. This has made my installation to take hours on lightsail using bitnami for django. What can I do to improve its installation. I hope that I have made my … -
Having issues retriving data from my database to the users
I am trying display all courses from my course model to the users, but seems i am getting it wrong. here is my code; views.py def course_list(request, category_slug=None): category = None categories = Category.objects.all() courses = Courses.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) courses = courses.filter(category=category) return render(request,'courses/content/list.html', {'category': category, 'categories': categories, 'courses': courses}) def course_detail(request, id, slug): course = get_object_or_404(Courses, id=id, slug=slug, available=True) return render(request, 'courses/content/detail.html', {'course': course}) here is the code for my list.html {%block content %} <section id="about-home"> <h2>Courses</h2> </section> <!-- courses section starts --> <section id="course"> <h1>Our Amazing Courses</h1> <p>Replenish man have thing gathering lights yielding shall you</p> <div class="course-box"> {% for course in courses %} <div onclick="window.location.href='{{ course.get_absoule.url}}';" class="courses"> <img src="{% if courses.cover %}{{ courses.cover.url }} {% else %} {% static 'images/c3.jpg' %}{% endif %}" alt="{{ courses.name }}" /> <div class="details"> <span>{{courses.updated}}</span> <a href="{{ course.get_absolute_url }}"></a> <h6>{{courses.name}}</h6> <div class="star"> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="far fa-star"></i> <span>(23)</span> </div> </div> <div class="cost">${{courses.price_display}}</div> </div> {% endfor %} </section> {%endblock content%} the above codes is for my views.py and list.html -
No file chosen This field is required
The Views from .models import Posts from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.messages.views import SuccessMessageMixin from django.views.generic import CreateView class PostCreateView(LoginRequiredMixin, CreateView): model = Posts fields = ['caption', 'image'] template_name = 'home/creat_post.html' def form_valid(self,form): form.instance.user = self.request.user return super().form_valid(form) The models class Posts(models.Model): caption = models.CharField(max_length=2200) date_posted = models.DateTimeField(default=timezone.now()) image = models.ImageField( upload_to='PostsImages') user = ForeignKey(User, on_delete=models.CASCADE ,related_name='UserPosts') def __str__(self): return f"Post {self.id} ({self.user.username})'s" def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) img.save(self.image.path) So I am able to add in the admin page normally and see the posts in the home.. but when I try to create post from using this class --> every time I add image and hit post, it tells me this field is requird Image of what I see -
django application only working with port 8000
I am working on an project and I have hosted it on ec2 to see if everything is working fine or not. It's only a single page application for now with no endpoint. Problem is it only works if I use my_domain:8000 or my_ip:8000 here is the config file i have written. server { listen 8000; server_name mydomain.info; # to avoid any error while fetching fevicon location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/dev/myproject; } location / { include proxy_params; # communicate via socket file created by Gunicorn proxy_pass http://unix:/home/ubuntu/dev/myproject.sock; } } I enabled it using: sudo ln -s /etc/nginx/sites-available/config-file /etc/nginx/sites-enabled/ after doing that I restarted nginx using- sudo systemctl restart nginx then started server using- python3 manage.py runserver 0.0.0.0:8000 It's my first time doing this and I think I have done something wrong with config file or while enabling it but I can't figure it out. -
Can I learn Python by myself?
Im an absolute beginner at Python. I start watching some videos on youtube. Please, can you tell me if I can learn Python by myself? Can you help me with websites? if yes, which course should I enrol in? Thank you, Rubi -
How to encode and decode an image in JSON for celery and django
I am trying to apply some logic to the image recieved from API call. Below is the code from the Django Rest Framework. I am trying to serialize the image so I can send it to a celery task but I am not serializing and deserialzing the image correctly. serializer.validated_data is <InMemoryUploadedFile: 1.png (image/png)>)]) serializer.validated_data['picture'].file is <_io.BytesIO object at 0x7f1375e1edb0> if serializer.is_valid(): image_uploaded = serializer.validated_data['picture'].file json_data = base64.b64encode(image_uploaded.read()).decode('ascii') call = test_func.delay(json_data) results = TestSerializer(TestModel.objects.get(pk=call.get())) @shared_task() def test_func(json_data): img_temp = asarray(Image.open(json_data)) ....some logic return model_instance.id I get the following error on the call.get() OSError: [Errno 36] File name too long I am not sure how to correctly serialize and derialize the image. Can someone please show how to fix this? -
In Openedx Based Project, Xblock customization need to add CKEditor in textarea in javascript
In Openedx Based Project, Xblock customization needs to add CKEditor in textarea in javascript. i am using this xblock "edx-sga Staff Graded Assignment XBlock" need to add one textarea in as a richtext-editor like CKEditor. -
Django-postgres-extesion ArrayRemove
Hey I'm trying to add network monitoring parameter values (int) into a Django models ArrayField every minute for further processing. Django-postgres-extension sounded promising for my purposes, but now I'm struggling with couple of issues. Im adding values (int) to my array using MyMeasData.objects.filter(ipAddress=ipa).update(paramOne = ArrayPrepend(param1, 'ParamOne')) but I need to keep my array length under n samples by removing last value of the array. Q1: what is the correct syntax to remove last value of the Array. All my attempts have failed, MyMeasData.objects.filter(ipAddress=ipa).update(paramOne = ArrayRemove('paramOne', [-1])) Q2: How do I get the size of queryset paramOne, so I know when to start ArrayRemove in Q1 MyMeasData.objects.filter(ipAddress = ipa).values_list('paramOne', flat = True) gives a queryset: <QuerySet [[903, 903, 901, 903, 901, 901, 901, 899]]> I have looked into the django-postgres-extension documentation, but wasn't able figure out the correct syntax. Im using (python 3.8.8, django 3.2.7) Any help would be highly appreciated! -
Uploading image with react "File extension “” is not allowed error
I am trying to upload an image from react to django. Here is my drop function: drop = async (files) => { console.log(files[0].name) <- correctly prints out "car.png" const object_image = URL.createObjectURL(files[0]) const FILES = { "uploaded_image": [{ image: object_image, address: await fetch(object_image).then(res => res.blob()) }] } And below is how I try to send it sendTheImage= () => { let formData = new FormData() formData.append('picture', this.state.files[0].address) axios.post("api/call", formData, { headers: { 'accept': 'application/json', 'content-type': 'multipart/form-data' } }) The error is File extension “” is not allowed. Allowed extensions are ...,png,.... Which shows that react is not able to get the file extension to send it to the Django backend. Am I creating the blob correctly? how to fix this issue? -
Incorrect Authentication Data
I tryng to send email in my django projects. Here is my settings:- EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'gmail.com' # EMAIL_USE_TLS = True EMAIL_USE_SSL = True EMAIL_PORT = 465 EMAIL_HOST_USER = 'noreply.marketage@gmail.com' EMAIL_HOST_PASSWORD = '*******' I am getting this error (535, b'Incorrect authentication data') I turned on less secure app also. I also tried my cpanel Email. For that my setting was # EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # EMAIL_HOST = 'mail.marketage.io' # EMAIL_PORT = 587 # EMAIL_USE_TLS = True # # EMAIL_USE_SSL = True # EMAIL_HOST_USER = 'noreply@marketage.io' # EMAIL_HOST_PASSWORD = '*******' # DEFAULT_FROM_EMAIL = EMAIL_HOST_USER For this settings I get the same error. I dont know what causing this issue. But My email was working 4 days ago and it worked just fine. But Suddenly Its not working. I tried to debug my code for that I used Gmail SMTP in my localhost. In Localhost its working completely fine but its not working when I try to send email from live server. Is there any solution?? Thanks In Advance -
How to join on multiple column with a groupby in Django/Postgres
I have the following tables that I need to join on date and currency: Transactions Description | Date | Amount | Currency Exchange rates Currency | Date | Rate I need to join on both the date and currency columns, multiply the rate and the amount and sum that up to get the total value in the different currency. I also need to group it per calendar month. Is this possible using the Django ORM or would I need to use SQL directly? If so, how do I go about doing this in Postgres? -
How to add Django to a react project? [closed]
I have a project which we started with React and firebase. We want to add Django for the backend instead of react and just keep React for front end (which I'm pretty sure is possible from what I've heard?) but my programmer had to step back due to her mental health. So, I now need to be the one doing it and I have a really hard time understanding how to. I'm still a beginner. Does anyone know of any good tutorials, or is able to explain how to do it? I tried searching but I can only find tutorials for adding react to a Django project, not the other way around. Thanks in advance! -
Unable to setup https and enable ssl on Apache mod_wsgi django server
I want to setup https and enable ssl for my django application which runs on a apache mod_wsgi server. I have my ssl certificates in my project directory. Here is the command which I use for starting the server(only mentioned ssl and https parameters):- ./manage.py runmodwsgi --https-only --https-port 8443 --ssl-port 8443 --ssl-certificate-chain-file /apps/django_app/keystore/ROOT-CA.pem --ssl-ca-certificate-file /apps/django_app/keystore/Intermediate-CA.pem --ssl-certificate-key-file /apps/django_app/keystore/server_name.keystore --ssl-certificate-file /apps/django_app/keystore/server_name.crt Here is the output which I get on executing the above command:- Successfully ran command. Server URL : http://0.0.0.0:8000/ Server URL (HTTPS) : https://0.0.0.0:8443/ Server Root : /tmp/mod_wsgi-0.0.0.0:8000:40000 Server Conf : /tmp/mod_wsgi-0.0.0.0:8000:40000/httpd.conf Though the http one runs fine on port 8000, but the https one fails and does not run on port 8443. Please let me know where I may be going wrong. -
how Add Links to a Bootstrap Navigation Bar in django?
i tried to Add Links to a Bootstrap Navigation Bar for login page of Django that finally save in Django administration here is my base.html file <html> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> {%block head %} <title>Base</title> {% endblock %} </head> <body> <br> <div class="container"> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/">Social Network</a> </div> <div id="navbar" class="navbar-collapse collapse"> {%if user.is_authenticated %} <ul class="nav navbar-nav "> <li><a href="/account">Home</a></li> <li><a href="/account/login">login</a></li> <li><a href="/account/profile">profile</a></li> <li><a href="/account/profile/edit">edit profile</a></li> <li><a href="/account/logout">logout</a></li> </ul> {% else %} <ul class="nav navbar-nav navbar-right"> <li><a href="/account/login">login</a></li> <li><a href="/account/register">Register</a></li> </ul> {% endif %} </div><!--/.nav-collapse --> </div><!--/.container-fluid --> </nav> {% block body%} <h1>Base</h1> {% endblock %} </body> </html> before it worked not very sort but it worked i checked another questions but i couldnt find my solution -
Django admin with multi-tenancy support, roles and action logs?
I'm looking to find an alternate solution to the built-in Django admin. We have a few main requirements with this admin panel. I understand that no admin panel would come with all solutions out-of-the-box, my goal is to find the one that gives the biggest jump start and takes the least effort to customize upon. I'm looking into multiple admin panels for Django, but most of them are UI refinements or with some extra features. I would like to kindly ask here if anyone know of the admin panel that closely fit what we need that I might have missed. A few main requirements: We use django_tenants for multi-tenancy, but we want the super admin to be able to access an individual tenant. For example, each tenant is our client, and our client want us to update some information for them. We would use the admin panel to update the data inside their tenant on their behalf Roles. We want to have multiple admins and not everyone would be super admin. One person might only be able to access information but not edit any, while another might be able to edit a few selected tables, etc. Action logs. When an … -
memoryview' object has no attribute 'decode' in django postgres
memoryview' object has no attribute 'decode' I am geeting this error while decoding the data from db which is of binary field inst=Instance.objects.all().filter(product=product,site=site) logger.info(inst) instance_file_data={} for ins in inst: instance_i.append(ins.Instance) logger.info(instance_i) strdat=FD.file_data.DECODE('ascii') -
Incremental totals in Django Model
I have a table as below: Example Table and I have a model as class Hours(models.Model): name = model.Charfield(max_length =200) hours = DecimalField(max_digits = 6, decimal_places=2) def total_hours(self): queryset = Hours.objects.aggregate(total_hours=models.Sum('hours')) return queryset['total_hours'] now when I run the code I get all records have the to 37 instead of them having a running total. where did I miss a step? -
Best practice of database design in django rest project?
I have a project where users has multiple permissions based on role assigned. Admin can assign rights(for e.g. can_view, can_approve) in some menu to some role and so on. In this way there can be so many bool flags and some of the flags will be unnecessary for some menu. If I go in like Django Group and permissions model base then there can be so many permissions. For example : ( can create menua , can update menub...) OR any other way which will be appropriate ? class User(): id name role_id(fk) class DashboardMenu(): id name codename(unique) url parent_id class Role(): id name(unique) desc menus(menu_ids (many to many)) class RoleMenuRight(): id role_id(fk) menu_id(fk) can_create can_delete can_update can_view can_approve can_reject #other bool flags Another approach class User(): id name role_id(fk) class Permission(): id name codename(unique) class Role(): id name(unique) desc permissions(permission_ids (many to many)) -
Django: Calculating the amount of the goods
You need to automatically calculate the order amount, redefined the save function, but swears at the lack of id. needs to have a value for field "id" before this many-to-many relationship can be used. class Pizza(models.Model): title = models.CharField(verbose_name='Название пиццы', max_length=100) technology_card = models.ForeignKey(Technology_card, on_delete=models.CASCADE) time_production = models.PositiveIntegerField(verbose_name='Время изготовления', default=10) time_baking_time = models.PositiveIntegerField(verbose_name='Время выпекания', default=10) price = models.DecimalField(verbose_name='Цена', max_digits = 10, decimal_places=2, default = 0) def __str__(self): return self.title class Meta(): verbose_name = 'Пицца' verbose_name_plural = 'Пицца' class OrderPizza(models.Model): STATUS_ACCEPT = 'Принят' STATUS_COOK = 'Готовится' STATUS_PREPARED = 'Приготовлен' STATUS_DELIVERED = 'Доставляется' STATUS_EXECUTE = 'Исполнен' STATUS_CHOISES = ( (STATUS_ACCEPT, 'Принят'), (STATUS_COOK, 'Готовится'), (STATUS_PREPARED, 'Приготовлен'), (STATUS_DELIVERED, 'Доставляется'), (STATUS_EXECUTE, 'Исполнен') ) id = models.AutoField(primary_key=True) date = models.DateField(verbose_name='Дата заказа', null=False, default = timezone.now()) name = models.CharField(verbose_name='Имя заказчика', max_length=50) surname = models.CharField(verbose_name='Фамилия заказчика', max_length=50) phone_number = models.CharField(verbose_name='Номер телефона', max_length=10) adress = models.CharField(verbose_name='Адрес доставки', max_length=40) order = models.ManyToManyField(Pizza) courier = models.ForeignKey(Courier, on_delete=models.CASCADE) status = models.CharField( verbose_name='Статус', max_length=12, choices=STATUS_CHOISES, default=STATUS_ACCEPT ) price = models.DecimalField(verbose_name='Стоимость заказа', default=0, max_digits = 10, decimal_places=2) def save(self, *args, **kwargs): self.price = sum([order.price for order in self.order.all()]) super(OrderPizza, self).save(*args, **kwargs) def __str__(self): return ('Заказ от {0} {1}').format(self.surname, self.date) class Meta(): verbose_name = 'Заказ пиццы' verbose_name_plural = 'Заказы пиццы' -
Why isn't my CSS, Javascipt, and bootstrap not showing up in my django site?
I'm using the Djanog for beginners book, it tells me to just copy and paste but when I do so, it doesn't work. The functionalities work(login, logout, etc) it's just the book shows the website being updated and looking way better than mine. Here's my base.html file: <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/\ bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81i\ uXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <title>{% block title %}Newspaper App{% endblock title %}</title> </head> <body> <nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4"> <a class="navbar-brand" href="{% url 'home' %}">Newspaper</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> {% if user.is_authenticated %} <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link dropdown-toggle" href="#" id="userMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{ user.username }} </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="userMenu"> <a class="dropdown-item" href="{% url 'password_change'%}">Change password</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'logout' %}"> Log Out</a> </div> </li> </ul> {% else %} <form class="form-inline ml-auto"> <a href="{% url 'login' %}" class="btn btn-outline-secondary"> Log In</a> <a href="{% url 'signup' %}" class="btn btn-primary ml-2"> Sign up</a> </form> {% endif %} </div> </nav> <div class="container"> {% block content %} {% endblock content %} </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4\ YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/\ 1.14.3/ umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbB\ JiSnjAK/ l8WvCWPIPm49" … -
approve or reject users through django-admin panel once the user signed up
as a newbie, I don't know to do this. I created one user model for users. after the user signed up it should goes up for admin approval. In the admin panel how to make two buttons approve or reject. Once the admin clicked approve button then only the user should be login to the site. if admin reject user won't be login. I need some help. models.py class Vendor(models.Model): name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) created_by = models.OneToOneField(User, related_name='vendor', on_delete=models.CASCADE) id = models.AutoField(primary_key=True, editable=False) vendorid= models.CharField(max_length=100, unique=True) class Meta: ordering = ['name'] def __str__(self): return self.name def save(self, *args, **kwargs): super().save(*args, **kwargs) if not self.vendorid: # if vendorid of the instance is blank self.vendorid = "VEN_ID" + str(self.id) # generating the vendorid and allocating the value self.save() # saving the instance def __str__(self): return self.vendorid -
How to build a search bar similar to Carvana
We are working on a class project in which we are building a car catalog for first-time car buyers(we are beginners at web dev). We are using Django for the backend and PostgreSQL for the database and vue.js for the front end. We are trying to make a filter bar similar to Caravana's search bar and wanted to know what type of component we could use in vuetify to get a similar look. We decided on dropdowns similar to the website and but ours would have only four options: Price (range slider) Make & Model (similar to carvana) Body style (buttons) door (range slider w/step) seats (range slider w/step) drive (buttons) Features Safety (range slider w/steps) Fuel (buttons) MPG City (range slider) Highway (range slider) Horsepower (range slider) Cylinder (buttons) Engine size (buttons) Engine loc (buttons) For example the the Body dropdown would have 4 subcomponents and each have a filter setting and so on. I guess the part we were confused on was how to get the sub-components with their different buttons under a dropdown like the features dropdown on the carvana website. Links to any blogs and tutorials or any advice for first time web developers would be … -
Create parent and child model in one form django
I am trying to build a form to create a recipe with a Recipe and RecipeIngredient model but when a user is creating a recipe how do I have them both in the same form since RecipeIngredient is dependent on the the foreign key of Recipe which is not yet initialized? Do I need to create a blank recipe everytime a user visits a create page to make this possible? models.py: class Recipe(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image = models.ImageField(upload_to='image/', blank=True, null=True) name = models.CharField(max_length=220) # grilled chicken pasta description = models.TextField(blank=True, null=True) class RecipeIngredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) name = models.CharField(max_length=220) # grilled chicken pasta description = models.TextField(blank=True, null=True) -
How to create a field that contain many values from other model in django
I start learning about django. I'm creating a quiz app in python django. In profile model I want to create two fields that is answered questions and incorrect questions. And these field must be contain many values from Question model. I try ManyToManyField but It doesn't give me correctly result. I'm using sqlite3. What is I can use to resolve this case? Thank you very much. Profile Model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='earth.png', upload_to='profile_images') bio = models.TextField() score = models.IntegerField(default=0,validators=[MinValueValidator(0)]) answered_ques = models.ManyToManyField('QuesModel', blank=True, related_name='Answered_Questions') Incorrect_ques = models.ManyToManyField('QuesModel', blank=True, related_name='Incorrect_Question') Question Model: class QuesModel(models.Model): question = models.CharField(max_length=500, null=True) op1 = models.CharField(max_length=500,null=True) op2 = models.CharField(max_length=500,null=True) op3 = models.CharField(max_length=500,null=True) op4 = models.CharField(max_length=500,null=True) ans = models.CharField(max_length=500,null=True) point = models.IntegerField(default=0, validators=[MaxValueValidator(100),MinValueValidator(0)]) -
Django annotate returning duplicate entries
I'm annotating a queryset like so: class ItemQuerySet(models.QuerySet): def annotate_subitem_stats(self): return self.annotate( count_subitems=Count('subitems'), has_sent_subitems=Case( When(subitems__status=Status.sent, then=Value(True)), default=Value(False) ), ) In this example, SubItem is a model with a foreign key to Item. A strange behaviour happens when I run this code. Suppose we have 1 Item and 2 SubItems linked to it. One subitem has status sent and the other doesn't. When I run annotate on the queryset, the queryset returns the item twice, one with has_sent_subitems set to True and the other set to False. The other strange thing is that, one duplicate has count_subitems == 1, and the other has count_subitems == 1, as if the queryset has split item into two rows, one where status == 'sent' and the other where status != 'sent'. This is basically what the annotated queryset looks like: [ { 'name': 'Item Name', 'count_subitems': 1, 'has_sent_subitem': False }, { 'name': 'Item Name', 'count_subitems': 1, 'has_sent_subitem': True } ] This is what the database looks like, using pseudocode: item = Item() SubItem(item=item, status=draft) SubItem(item=item, status=sent) I'm pretty sure this has to do with line When(subitems__status=Status.sent, then=Value(True)),. Is there any way I can make that line check if only 1 item has status sent, …