Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to compare the columns of three tables of the model through a loop and copy the current row if equal?
I have three table models. In one column of the table, the data is in the form - date-time (datetime). Each of the three tables has this column (datetime). Dates may vary slightly. And I need to copy the data from all three model tables into one empty model - only those rows - where the values in a certain column (datetime) are equal to each other for these three model tables. You can even do something similar by converting to a DataFrame . How to compare the columns of three tables of the model through a cycle and, if equal, send the current row to another model? -- datetime temper_1 temper_2 g_rashod temper_nv 0 2023-01-02 10:00:00 58.13 49.35 70.520 1.4 1 2023-01-02 11:00:00 57.44 49.12 89.805 1.4 2 2023-01-02 12:00:00 57.82 49.30 89.187 1.4 3 2023-01-02 13:00:00 58.08 49.62 89.079 1.4 4 2023-01-02 14:00:00 58.20 49.77 89.081 2.1 225 2023-10-02 19:00:00 65.67 53.90 87.998 -7.6 226 2023-10-02 20:00:00 66.80 54.98 87.970 -8.1 227 2023-10-02 21:00:00 67.37 55.53 87.946 -8.1 228 2023-10-02 22:00:00 67.76 55.87 87.973 -8.1 229 2023-10-02 23:00:00 68.02 56.09 87.942 -8.1 -- datetime rashod_gas 0 2023-01-02 00:00:00 71.44 1 2023-01-02 01:00:00 71.55 2 2023-01-02 02:00:00 71.60 3 … -
Problemas al momento de hacer manage.py check o manage.py migrate [closed]
buenas tardes estoy tratando de realizar un proyecto nuevo en django y hago un python3 manage.py migrate o python3 manage.py check para verificar si esta en correcto todo y me sale este error, ayuda por favor C:\Users\JOSE\sistemas\proyectoDjango\Test (test19) λ python3 manage.py check Traceback (most recent call last): File "C:\Users\JOSE\sistemas\proyectoDjango\Test\manage.py", line 22, in main() File "C:\Users\JOSE\sistemas\proyectoDjango\Test\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\JOSE\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra 8p0\LocalCache\local-packages\Python310\site-packages\django\core\management_init_.py", l ine 446, in execute_from_command_line utility.execute() File "C:\Users\JOSE\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra 8p0\LocalCache\local-packages\Python310\site-packages\django\core\management_init_.py", l ine 420, in execute django.setup() File "C:\Users\JOSE\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra 8p0\LocalCache\local-packages\Python310\site-packages\django_init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\JOSE\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra 8p0\LocalCache\local-packages\Python310\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\JOSE\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra 8p0\LocalCache\local-packages\Python310\site-packages\django\apps\config.py", line 169, in c reate if mod_path and cls_name[0].isupper(): IndexError: string index out of range intente con manage.py migrate me abre el editor de visual vasic extactamente enter image description here -
Django Correct Date / Time not PC date/time
Is there a way to get the exact date/time from the web rather than taking the PC date/time? I am creating a website where the answer is time relevant. But i don't want someone cheating by putting their pc clock back. When i do: today = datetime.datetime.today() or now = datetime.datetime.utcnow().replace(tzinfo=utc) i still get whatever time my pc is set to. Is there a way to get the correct date/time Thanks in advance for any help -
How can I make a password confirmation in Django to access an specific page?
I am looking to add a password confirmation before use can delete their account. I just found one tutorial for this, it is precisely what I want - add a password confirmation like GitHub's when we try to delete a repo or something else. https://simpleisbetterthancomplex.com/media/2016-08-15-how-to-create-a-password-confirmation-view/github.png But, I can not add a new field like in the tutorial. Is there another way that I can do it? For now, I've tried something, but I just got a 405 error. This is my view code: class ConfirmPasswordToDeleteAccountView(LoginRequiredMixin, FormView): form_class = Form template_name = 'dashboard/components/confirm_password_modal' def form_valid(self, form): user = self.request.user password = form.cleaned_data.get('password') if user.check_password(password): user.delete() logout(self.request) else: form.add_error('password', 'Incorrect password. Please try again.') return self.form_invalid(form) This is the modal where it is happening, but after submitting nothing happens, only a 405 error and the account is not deleted: <a href="#" onclick="return toggleModal()"> <button type="button" data-modal-target="authentication-modal" data-modal-toggle="authentication-modal" > Delete Account </button> </a> <div id="authentication-modal" tabindex="-1" aria-hidden="false"> <div> <div> <button type="button"> <svg aria-hidden="false" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg> <span>Close modal</span> </button> <div> … -
If i built a Django Website, can i make an api with Django Rest Framework of the same logic to make a mobile client later?
What i mean is lets say i have a totally functional and regular Django Web App. But then the client tells me they want a mobile client of the same app. So that means i should make an api, to get the data on the client. Django Rest Framework is the way to make api with Django, but i dont know if i can add the api layer after making the regular Django App and leverage or take advantage of the existing logic i have previously created so the both web app and api can coexist. Or if i should have started making the app with django rest framework from the begining.(Wich isnt convenient for me now). What do you think? What are my options? Thanks in advance! -
Error parsing template venv\Lib\site-packages\wagtail\admin\templates\wagtailadmin\bulk_actions\confirmation\form_with_fields.html: form.html
I am using Django for my main project but also wagtail for the blog section. I am also using sass in my project. When I run the command ./manage.py compilescss, I get the above error. There are no form templates in my project and this is obviously referencing wagtail so I don't really know how to remove the error. Anyone have any ideas? -
Django: A None DateInput does not pass through form validate. How can I fix it?
I use UpdateView and created a field called date_updated. When the user creates, e.g., a Group, there are zero updates. In models.py I defined: date_updated = models.DateTimeField(null=True) Then in forms.py I created the update form, e.g., class UpdateGroupForm(forms.ModelForm): class Meta: model = Group fields = ['name','date_updated'] In templates I call my form, as expected in the iteration {% for field in form %}, field.value = None for the specific field date_updated, and because of this I believe is not updating. In views.py I have the following in the UpdateGroup class def form_valid(self, form): if form.instance.owner == self.request.user: form.instance.date_updated = timezone.now() return super().form_valid(form) else: return super().form_invalid(form) I tried to replace the empty value with a fake date considering in my templates the following: {% if field.name == 'date_updated' and field.value == None %} <input type="date" name="date_updated" value="2000-01-01" format="yyyy-mm-dd" required disabled> {% else %} But it doesn't work also, I cannot validate the form and update my values with the first update.. What can I do? The only thing that works is to remove date_updated from forms.py, do the first updated and then restore it forms.py. Now because is not an empty Date everything works and I can proceed with a second … -
Null is passed to todos_id while submitting form eventhough i've changed it
this is my view which is createview and i've used custom form and send current user id to the form class createToDo(CreateView): success_url = 'home' form_class = ToDoForm template_name = 'home.html' user_id = None test = 'vaseem' def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['user_id'] = self.user_id return kwargs def get(self, request: HttpRequest, *args: str, **kwargs) -> HttpResponse: self.user_id = request.user.id return super().get(request, *args, **kwargs) this is my form class ToDoForm(ModelForm): todos_id = forms.CharField(widget=forms.TextInput(attrs={'value':'test'})) title = forms.CharField(widget=forms.TextInput(attrs={'id':'title'})) description = forms.CharField(widget=forms.Textarea(attrs= {'id':'description','cols':30,'rows':2})) date = forms.DateField(widget=forms.DateInput(attrs={'type':'date'})) class Meta(): model = ToDo fields = ('title','description','date','todos_id') def __init__(self,user_id = None,*args, **kwargs): self.id_data = user_id super(ToDoForm,self).__init__(*args,**kwargs) self.fields['todos_id']= forms.CharField(widget=forms.TextInput(attrs= {'value':self.id_data,'style':'display:none;'})) this is the post-data,from this data it is clear value is not none then what is the problem Variable Value csrfmiddlewaretoken 'QCBi8WL9GYK0LdRx1FQq7sXDNjSaKjjv8IWnLwQ63toz43uNhGtM1H8C50c54zUC' todos_id 'None' title 'test' description 'testdesc' date '2023-02-23' this is my model which is connected to my user moodel class ToDo(models.Model): todos = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=75,null=False) description = models.TextField(null=False) date = models.DateField(null=False) done = models.BooleanField(default=False) this is the error showing, eventhough i can see the value in the todos_id input while inspecting IntegrityError at /createToDo null value in column "todos_id" of relation "ToDoApp_todo" violates not-null constraint DETAIL: Failing row contains (21, test, testdesc, 2023-02-23, f, … -
Save data from several models to one summary by the smallest size of one of this?
I have three databases - table models. In which there is a different amount of data - a different number of rows of elements in the database table. One table has 100 rows - the other model table has 150 rows. I’m going to transfer the data from these models to another one - a general summary table model. Sequentially transferring data from each model. How can I do this - to transfer data to the summary table - only by the size (number of rows) of the smallest model table? -- def file_upload_button(request): context = {} queryset_summ = Model_upload_summ.objects.all() queryset_1 = Model_upload_teplo.objects.all() queryset_2 = Model_upload_gvs.objects.all() queryset_3 = Model_upload_topgas.objects.all() datetime_1 = [d.datetime for d in queryset_1] datetime_2 = [d.datetime for d in queryset_2] datetime_3 = [d.datetime for d in queryset_3] numbers_1 = len(datetime_1) numbers_2 = len(datetime_2) numbers_3 = len(datetime_3) if numbers_1 <= numbers_2 and numbers_1 <= numbers_3: # save numbers_1 (rows of queryset Models) into queryset_summ or Model_upload_summ elif numbers_2 <= numbers_1 and numbers_2 <= numbers_3: # not active if first condition (above) id done elif numbers_3 <= numbers_1 and numbers_3 <= numbers_2: # not active if first condition (above) id done -
Filtering site with specific tags in Django while keeping all site tags aggregated in annotation field
Let's say I have the following django model: class Tag(models.Model): key = models.CharField(max_length=64, unique=True) class Site(models.Model): key = models.CharField(max_length=64, unique=True) tags = models.ManyToManyField(Tag, through='SiteTag') class SiteTag(models.Model): site = models.ForeignKey(Site, on_delete=models.RESTRICT) tag = models.ForeignKey(Tag, on_delete=models.RESTRICT) Where a site can have multiple tags using explicit Many-to-Many relationship. When I filter site with a specific tag in the following query other tags are filtered out where I mean give me sites with this tags and show all tags those sites have: Site.objects.filter(tags__key__in=['type-1', 'type-2'])\ .annotate(tags=ArrayAgg("tags__key", distinct=True, filter=Q(tags__isnull=False))) Then it indeed retrieve sites with either type-1 or type-2 but if a selected site has the type-3 tag I also want to collect it in the ArrayAgg aggregation. Unfortunetly with this query I will only have ["type-1", "type-2"] in annotated tags field instead of ["type-1", "type-2", "type-3"]. How can I filter sites using this criterion and still have all tags collected in the annotate section. -
How to send data to a particular user in django channels?
This is my class: class MyClass(models.Model): name = models.CharField(max_length=128, unique=True) members = models.ManyToManyField("Employee") def save(self, *args, **kwargs): super().save(*args,**kwargs) channel_layer = get_channel_layer() data = {"current_obj":self.name} async_to_sync(channel_layer.group_send)( "test_consumer_group_1",{ 'type':'send_notification', 'value':json.dumps(data) } ) This is my consumer file. class TestConsumer(WebsocketConsumer): def connect(self): self.room_name="test_consumer" self.room_group_name = "test_consumer_group_1" async_to_sync(self.channel_layer.group_add)( self.channel_name, self.room_group_name ) self.accept() print('connected..') self.send(text_data=json.dumps({'status':'connected'})) def recieve(self, text_data): print(text_data) def disconnect(self, *args, **kwargs): print('disconnected') def send_notification(self, event): print("send_notification called") print('Event...', event['value']) user = self.scope['user'] print(user) # Check if the user is authenticated and is a member of the team ''' if user.is_authenticated and user.employee in self.team.members.all(): self.send({ "type":"websocket.send", "text":event['value'] }) ''' This is my asgi.py file: import os import app.routing from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") application = get_asgi_application() application = ProtocolTypeRouter({ 'http': get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( app.routing.websocket_urlpatterns ) ), }) When an object of MyClass is created, send_notification is called. Now I want to ask two things: Inside send_notification, user = self.scope['user'] always returns anonymous user, even if user is authenticated. I want to send notification to particular users onlyi.e. employees who are added in MyClass object and are logged in, instead of broadcasting the message How to do that? -
Django dynamic model fields dependent on uploaded data in other model
I would like to create a model with fields that correspond to the column names of a csv file that is uploaded by the user. I use the model CsvCreate to let the user upload a csv file and to create instances of the model Data, where an instance is a row in the csv file. This works fine, but I have to specify the fields in Data beforehand. However, the column names in the csv file could vary. What I want is to have a model with dynamic fields that are dependent on the uploaded csv file. Model CsvCreate: class CsvCreate(models.Model): file_name = models.FileField(upload_to='csvs') uploaded = models.DateTimeField(auto_now_add=True) selected = models.BooleanField(default=False) measurement_number = models.IntegerField(blank=True, null=True) notes = models.TextField(blank=True, null=True) dataset = models.ForeignKey('Dataset', on_delete=models.CASCADE) units = models.CharField(max_length=100, blank=True, null=True ) def __str__(self): return f"File name: {self.file_name}, file id: {self.id}, uploaded at {self.uploaded}, selected: {self.selected}" def save_csvs(self): obj = self with open(obj.file_name.path, 'r') as f: reader = csv.reader(f) values = [obj] units = [] dict_list = [] for i, row in enumerate(reader): if i < 2: pass elif i == 2: for i in range(0,len(row)): units.append(row[i]) else: for i in range(0,len(row)): values.append(row[i]) data_dict = dict(zip(parameters.parameters, values)) dict_list.append(data_dict) values = [obj] django_list = … -
ATOM PACKAGE INSTALLATION
I am unable to find packages in ATOM. It continuously showing some certifications error .Can anyone help me out please Please ans to my question with necessary solutions -
Chromedriver error on Django DigitalOcean App Platform
I'm currently developping a web app using django and the App platform on digitalocean. My web app uses selenium and chromedriver, I have found a way to install chromedriver using python libs such as chromedriver_binary on pip but the app can't open it and throws me an error : Message: Service chromedriver unexpectedly exited. Status code was: 127 This error most likely means that some dependencies and libs are not available and leads to the script crashing. Here's my current code inside views.py : from selenium import webdriver import chromedriver_binary import time from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium_stealth import stealth import undetected_chromedriver as uc from selenium.webdriver.chromium.options import ChromiumOptions from selenium.webdriver.common.by import By import urllib.request from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from selenium.common.exceptions import UnexpectedAlertPresentException from selenium.common.exceptions import NoSuchElementException from googleapiclient.discovery import build from urllib.parse import urlsplit def get_webdriver(url): options = webdriver.ChromeOptions() options.add_argument('--disable-extensions') options.add_argument('--headless') options.add_argument('--disable-gpu') options.add_argument('--no-sandbox') options.add_argument('start-maximized') options.add_argument('disable-infobars') options.add_argument('--disable-dev-shm-usage') options.add_argument('--disable-browser-side-navigation') options.add_argument('--disable-gpu') driver = webdriver.Chrome() driver.get(url) return driver Is there a way (maybe using another lib, or a whole other solution) to deploy chromedriver on this django app ? Thank you a lot ! -
How to handle 300 parameters in Django Model / Form?
I develop an app for creating products in online shop. Let's suppose I have 50 categories of products and each of these has some required parameters for product (like color, size, etc.). Some parameters apper in all categories, and some are unique. That gives me around 300 parameters (fields) that should be defined in Django model. I suppose it is not good idea to create one big database with 300 fields and add products that have 1-15 parameters there (leaving remaining fields empty). What would be the best way to handle it? What would be the best way to display form that will ask only for parameters required in given category? -
I followed the django example exactly. But it doesn't work
** I followed the django example exactly. But it doesn't work. Web page just show the rocket to me.** my project name: web app name: main web.settings.py `INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', ]` web.urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('main/', include('main.urls')), path('admin/', admin.site.urls), ] main.urls.py => from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] main.views.py from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") I hope web page shows "Hello, world. You're at the polls index." to me. -
How do you manage testing error Django projects?
I need to create a blog post app in which I am stuck in testing all test cases , I need a user which can remain logged in throughout the testing phase so that I can use the same logged in user in blog and post and update_post apis but I am unable to do so can you please suggest !! def test_login(client, user_data): # with unittest.mock.patch('django.contrib.auth.authenticate') as mock_authenticate: # mock_authenticate.return_value = authenticate( # request=client.post(reverse('login'), user_data, format='json'), # backend='django.contrib.auth.backends.ModelBackend' # ) with unittest.mock.patch('django.contrib.auth.authenticate') as mock_authenticate: user = CustomUser.objects.create_user(**user_data) mock_authenticate.return_value = user response = client.post(reverse('login'), user_data, format="json") assert response.sstatus_code == 200 this is my login api and I want this user to be logged in throughout all apis without using SESSIONS -
Can't filter empty fields in Django
I want to get a list of users that have provided an email in my database using Django. This is my query: list(App.objects.exclude(admins__email='').values('admins__email')) which strangely exclude everything and gives : [] although when i run: list(App.objects.all().values('admins__email')) i can see a list of user emails and NOT all of them are empty: [{'admins__email': 'example@gamil.com'}, {'admins__email': ''}, {'admins__email': ''}, {'admins__email': ''}, {'admins__email': 'example2@gamil.com'}, {'admins__email': 'example3@gamil.com'}, {'admins__email': ''}, ...] i expect to get this list: [{'admins__email': 'example@gamil.com'}, {'admins__email': 'example2@gamil.com'}, {'admins__email': 'example3@gamil.com'}] ps: somehow i can get the correct list with list(User.objects.exclude(email__exact='').values('email')) but in this context, I need to apply some filters to my App and therefore i need to get the first query to work. -
django orm multiple points ranking
I've a model name Points which store the user points on the base of it's actions. class Points(CreateUpdateModelMixin): class Action(models.TextChoices): BASE = 'BASE', _('Base') REVIEW = 'REVIEW', _('Review') FOLLOW = 'FOLLOW', _('Follow') VERIFIED_REVIEW = 'VERIFIED_REVIEW', _('Verified Review') REFERRAL = 'REFERRAL', _('Referral') ADD = 'ADD', _('Add') SUBTRACT = 'SUBTRACT', _('Subtract') user = models.ForeignKey(User, on_delete=models.CASCADE) points = models.IntegerField() action = models.CharField(max_length=64, choices=Action.choices, default=Action.BASE) class Meta: db_table = "diner_points" Please note that there are multiple rows for the same user. For the past few days I'm trying to write a query to get the total_points of the use and also the rank of that user. Using: Django 3.2 MySQL 5.7 I want to know input of you guys. Thanks. I wrote this query and many other like it. But none of them give the results I want. Let's suppose the data is something like this. user points 771 221 1083 160 1083 12 1083 10 771 -15 1083 4 1083 -10 124 0 23 1771 The current query I have written is this... innerquery = ( DinerPoint.objects .values("user") .annotate(total=Sum("points")) .distinct() ) query = ( DinerPoint.objects .annotate( total = Subquery( innerquery.filter(user=OuterRef("user")).values("total") ), rank = Subquery( DinerPoint.objects .annotate( total = Subquery( innerquery.filter(user=OuterRef("user")).values("total") ), rank=Func(F("user"), function="Count") … -
Django returns model objects in random order after app rename
I've renamed an app in my Django project, trying to follow all 'best practices', that is, I renamed project folders, migrations (in project + PostgreSQL), DB content types and table names. Everything works fine, except one thing: the order of the objects returned by myfavmodel.objects.all() appears to be random, that is, NOT sorted by increasing ID, yet it is always the same when I call myfavmodel.objects.all(). Even more strange is that some models in the renamed app show this behaviour while others show the normal one, that is, their objects are returned sorted by increasing ID. I can solve the problem rather easily by adding ordering = ['id'] to the Meta class of my models but I would like to understand what is causing this behaviour. -
After running "python manage.pr makemigrations" indjango, models are still left un migrated with this message on CLI
It is impossible to add a non-nullable field 'core' to event without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit and manually define a default value in models.py. enter image description here my models -
How to make Django view accessible only when a GET request is issued by HTMX?
I am trying to learn HTMX for using it with Django. I have a simple HTMX button that when you click you get some filtered results on the page. The problem is that when users go to the specified URL provided for the purpose of showing content through the GET request, they can see the content of the page. They should only be able to see this content when they press the HTMX button though, not by navigating to the URL HTMX gets in order to show the content. Is there any way on how to handle this? -
How to change json view in django serializer?
This is my serializer.py class RefbookSerializer(serializers.ModelSerializer): class Meta: model = Refbook fields = ['id', 'code', 'name'] And it's my views.py class RefbookAPIList(ListCreateAPIView): queryset = Refbook.objects.all() serializer_class = RefbookSerializer def get_queryset(self): date = self.request.query_params.get('date', None) if date: query = Refbook.objects.filter(versions__date__lte=date).distinct() return query return super().get_queryset() Now, on request GET api/v1/refbooks/?date=2023-02-01 it returns a response like: [ { "id": 3, "code": "1", "name": "..." }, { "id": 4, "code": "2", "name": "..." } ] But i want like this: { "refbooks": [ { "id": 3, "code": "1", "name": "..." }, { "id": 4, "code": "2", "name": "..." } ] } How can i add this "refbooks" key and curly braces around it? -
Form with different target urls to send the POST to
I have one view displaying a form. Now, depending on the button the user chooses, I want to have the data processed in a different way. These "different ways" correspond with different views that I want the POST request go to. Please help me building a form with multiple buttons leading to different urls/views. <form action="/your-name/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Process form with view ONE"> <input type="submit" value="Process form with view TWO"> <input type="submit" value="Process form with view THREE"> </form> My problem here is that the action attribute of the form tag defines where this POST request is going to. How can I change that target url via multiple buttons? I know I could also handle this logic on the server-side. But the question is: Do I have to? If not, please show me the way -
Django filter query using Q
Can anyone help me. Im trying to use a django filter with Q. This is my function def get_first_time_customer_ids(year: int, month: int) -> QuerySet: return Customer.objects.filter( Q(bookings__status=Booking.STATUS.completed, bookings__pickup_time__year=year, bookings__pickup_time__month=month) & ~Q(bookings__status=Booking.STATUS.completed, bookings__pickup_time__lt=date(year, month, 1)) ).distinct().values_list('id', flat=True) What im trying to achieve is to yield all the customer id that have the first time booking for any given year and month. But its failing on my test case. My test case : def test_get_first_time_customer_ids(self) -> None: customer_1 = Customer.objects.create(name="Customer 1") customer_2 = Customer.objects.create(name="Customer 2") Booking.objects.bulk_create([ Booking(number="A", customer=customer_1, price=100_000, status=Booking.STATUS.completed, pickup_time=dt(2023, 2, 4, 12), route_id=1, vehicle_category_id=1), Booking(number="B", customer=customer_1, price=100_000, status=Booking.STATUS.completed, pickup_time=dt(2023, 1, 5, 12), route_id=1, vehicle_category_id=1), Booking(number="E", customer=customer_2, price=100_000, status=Booking.STATUS.completed, pickup_time=dt(2023, 2, 10, 12), route_id=1, vehicle_category_id=1) ]) ids = get_first_time_customer_ids(2023, 2) self.assertTrue(customer_2.id in ids) self.assertFalse(customer_1.id in ids) Its failing in the last line. The customer id for customer_1 included in query, it shouldnt have. Any help is appreciated