Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django URL dispatcher and lists?
I'm unsure if the title terminology makes much sense. But I have a pretty loose grasp on the URL dispatcher and if what I'm really asking here is in regards to the dispatcher or not really. Here is my views file: def current_game_table(request): items = list(Nbav8.objects.using('totals').all()) # rest of your code return render(request, 'home/testing.html', {'items': items}) def your_details_view(request, pk): item = Nbav8.objects.using('totals').get(pk=pk) current_day_home_team = list(Nbav8.objects.using('totals').values_list('home_team_field', flat=True)) current_day_away_team = list(Nbav8.objects.using('totals').values_list('away_team_field', flat=True)) awayuyu = [] homeuyu = [] for team in current_day_home_team: home_team_list1 = PreviousLossesNbav1WithDateAgg.objects.using('totals').filter(Q(away_team_field=team) | Q(home_team_field=team)).values_list('actual_over_under_result_field', flat=True) homeuyu.append(list(home_team_list1[:5])) home_team_list2 = homeuyu typeitem = type(item) typehome = type(current_day_home_team) for team in current_day_away_team: away_team_list1 = PreviousLossesNbav1WithDateAgg.objects.using('totals').filter(Q(away_team_field=team) | Q(home_team_field=team)).values_list('actual_over_under_result_field', flat=True) away_teamdd = away_team_list1[:5] awayuyu.append(list(away_team_list1[:5])) away_team_list2 = awayuyu return render(request, 'home/testing2.html', {'item': item, 'away': away_team_list2, 'home': home_team_list2, 'type1': typeitem, 'type2': typehome, 'eep': current_day_home_team}) Here is my testing.html Hello World {{ items }} {% for item in items %} <a href="{% url 'your_details_view' item.pk %}">{{ item.home_team_field }}</a> {% endfor %} Here is testing2.html <p>The price of this item is: {{ item }}</p> <p>The price of this item is: {{ home }}</p> <p>The price of this item is: {{ away }}</p> {{ eep }} <a href="{% url 'your_details_view' item.pk %}">{{ away }}</a> And here is my url … -
Django get current Model ID
Good Day, I have a delete btn for each created Title. When you click on the delete button, the model will be delete with the url localhost:8000/delete/OBJECT_ID models.py class NewTitle(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) title = models.CharField(max_length=200) creator_adress = models.GenericIPAddressField(null=True) id = models.BigAutoField(primary_key=True) def __str__(self): return str(self.title) views.py def title_view(request): custom_title_id = random.randint(1111, 1111111111111) titles = # What to here, maybe NewTitle.pk? if request.method == 'POST': form = NewTitleForm(request.POST, instance=NewTitle(user=request.user)) if form.is_valid(): obj = form.save(commit=False) obj.creator_adress = get_client_ip(request) obj.id = custom_title_id while NewTitle.objects.filter(id=obj.id).exists(): obj.id = random.randint(111, 11111111111) obj.save() return redirect('/another') else: form = NewTitleForm() return render(request, 'test.html', {'form': form, 'titles': titles}) def title_delete(request, title_id): user_title = NewTitle.objects.filter(id=title_id, user=request.user) if user_title: user_title.delete() else: return redirect('https://example.com') return HttpResponseRedirect('/another') test.html {% for i in request.user.newtitle_set.all %} <p> {% if i.user == request.user %} {{ i.title }} {% endif %} <form action="delete/ #THE CURRENT OBJECT ID" method="POST">{% csrf_token %}<button type="submit">Delete Title</button></form> </p> {% endfor %} Every 'Title' is displayed in the template. Next to each title there is a Delete button that leads to delete/OBJECT_ID. How can I set the action="" to the correct delete URL. So that I get the current ID of the title (object). The interesting part … -
Why this Django Rest Framework simple serializer don't work with ViewSet?
I have to endpoints with Django REST: ProductViewSet and DeviceViewSet. They are as simple as a GET method with retrieve and list. While I was profiling, I did a bit of research and I decided to write my own very simple serializers (not from DRF) and the performance is highly improved. The ProductViewSet works perfectly for retrieve and list methods. The DeviceViewSet works for list but fails for retrieve because of the serializer. This is the error: Traceback (most recent call last): File "/home/everton/.virtualenvs/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/everton/.virtualenvs/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/everton/.virtualenvs/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/home/everton/.virtualenvs/venv/lib/python3.8/site-packages/django/template/response.py", line 106, in render self.content = self.rendered_content File "/home/everton/.virtualenvs/venv/lib/python3.8/site-packages/rest_framework/response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "/home/everton/.virtualenvs/venv/lib/python3.8/site-packages/rest_framework/renderers.py", line 723, in render context = self.get_context(data, accepted_media_type, renderer_context) File "/home/everton/.virtualenvs/venv/lib/python3.8/site-packages/rest_framework/renderers.py", line 655, in get_context raw_data_put_form = self.get_raw_data_form(data, view, 'PUT', request) File "/home/everton/.virtualenvs/venv/lib/python3.8/site-packages/rest_framework/renderers.py", line 551, in get_raw_data_form serializer = view.get_serializer(instance=instance) File "/home/everton/Documents/django/django_app/userapi/views.py", line 293, in get_serializer return self.serializer_class(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'instance' Everything is nearly identical excel the DeviceSerializer uses the ProductSerializer because of a ForeignKey field. I can't seem to find the … -
How to loop my django template from my dynamic forms
I got Forms.py something like this, I make dynamic for HomeTeam until LigaTeam. class CreateEvents(forms.Form): def __init__(self,*args,**kwargs): choices = kwargs.pop('choices') team = kwargs.pop('team') choicesAgent = [("%s" % x['_id'], "%s" % x['name']+" by: "+x['agentName']) for x in choices] teams = [("%s" % x['_id'], "%s" % x['name']) for x in team] super(CreateEvents,self).__init__(*args,**kwargs) self.fields['agent'].choices = choicesAgent # List Match Make Dynamic for i in range(0, 6): self.fields["homeTeam%d" % i] = forms.ChoiceField(label="Home Team %d" % i+1, widget=forms.Select(attrs={'class': "form-control"}), required=True) self.fields["homeTeam%d" % i].choices = teams self.fields["awayTeam%d" % i] = forms.ChoiceField(label="Home Away %d" % i+1, widget=forms.Select(attrs={'class': "form-control"}), required=True) self.fields["awayTeam%d" % i].choices = teams self.fields["matchDate%d" % i] = forms.DateField(label="Match Date %d" % i+1, initial=DateNow(4), widget=forms.TextInput(attrs={'placeholder': 'Input Match Date %d' % i+1,'class': "form-control"}), required=True) self.fields["matchTime%d" % i] = forms.TimeField(label="Match Time %d" % i+1, initial=TimeNow(), widget=forms.TextInput(attrs={'placeholder': 'Input Match Time %d' % i+1,'class': "form-control"}), required=True) self.fields["ligaName%d" % i] = forms.CharField(label="League Name %d" % i+1, max_length = 30, widget=forms.TextInput(attrs={'placeholder': 'Input League Name %d' % i+1,'class': "form-control"}), required=True) # Event Detail agent = forms.ChoiceField(label="Agent", widget=forms.Select(attrs={'class': "form-control"}), required=True) eventName = forms.CharField(label="Event Name", max_length = 30, widget=forms.TextInput(attrs={'placeholder': 'Input Event Name','class': "form-control"}), required=True) startDate = forms.DateField(label="Start Date", initial=DateNow(), widget=forms.TextInput(attrs={'placeholder': 'Input Start Date','class': "form-control"}), required=True) deadlineDate = forms.DateField(label="Deadline Date", initial=DateNow(4), widget=forms.TextInput(attrs={'placeholder': 'Input Deadline Date','class': "form-control"}), required=True) … -
Agrupar registros con suma [closed]
Necesito traer los registros de mi base de datos agrupados por un campo y sumando dos campos. actualmente tengo este código results = programacion.objects.filter(Q(codigo_recurso__recurso__icontains=recurso)).values('pk', 'programacion', 'codigo_hijo', 'turno_inicio', 'proyecto', 'pedido', 'orden_produccion','actual_start_time', 'actual_end_time', 'descripcion_hijo', 'rendimiento', 'cantidad_inicial', 'descripcion_orden_produccion', 'estado_job' ).order_by('orden_produccion') results = results.annotate(tiempo_un(60/Sum('rendimiento'))*Sum('cantidad_inicial')) Pero me todos los registros y no me agrupa por orden_produccion -
how I set path of different folder path other than static folder to download files in Django
how I set path of different folder other than static folder to download files in Django My files are created at the server where the mange.py file is placed.Each time file is changed according to user requirement I'm new to django help me . myproject -manage.py -myfile.aln myproject -setting.py -Urls.py myprojectApp -template -static -url.py -views.py Now I just want to download myfile.aln file that s in myproject folder .... now in template page how I set this folder path -
Problems changing the prefix of a formset in django
I have a question, what happens is that I have a formset and an empty_form (in the same HTML); I have them to do some calculations, for the empty_form I already managed to extract the ID and do operations but not for the formset, and that is that my main problem is that they have the different ID, for example for the formset is like this: id_form-0-quantity and for the empty_form it is: id__form-1-quantity (one more underscore) but with that different ID I have to make some changes in JS, which I don't want to do because I'm very new in JS and possibly messing up the code more. Is there a way to change the formset prefix to look like this: id__form-0-quantity?; I used the following line: formset = ParteFormSet(request.POST, request.FILES, prefix='__form') But absolutely nothing happens views def create_Presupuestos(request): extra_forms = 1 ParteFormSet = formset_factory(PresupuestosParteForm, extra=extra_forms, max_num=20) presupuestosclientesform=PresupuestosClientesForm(request.POST or None) presupuestosvehiculosform=PresupuestosVehiculosForm(request.POST or None) presupuestosparteform=PresupuestosParteForm(request.POST or None) presupuestosmanoobraform=PresupuestosManoObraForm(request.POST or None) presupuestospagosform=PresupuestosPagosForm(request.POST or None) if request.method == 'POST': formset = ParteFormSet(request.POST, request.FILES, prefix='__form') if formset.is_valid(): presupuestosclientesform.save() return redirect('presupuestos:index') else: formset = ParteFormSet() return render(request,'Presupuestos/new-customer.html',{'presupuestosclientesform':presupuestosclientesform,'presupuestosvehiculosform':presupuestosvehiculosform,'presupuestosparteform':presupuestosparteform,'presupuestosmanoobraform':presupuestosmanoobraform,'presupuestospagosform':presupuestospagosform,'formset':formset}) HTML <table class="table table-bordered table-nowrap align-middle" id="childTable1"> <thead class="table-info"> <tr> <th scope="col">Quantity</th> <th scope="col">Unit Price</th> </thead> <tbody> … -
How do you send a custom attribute to the Django admin site context?
I would like to send a custom attribute (True or Flalse) to the Django admin website so that it can be access in a custom template as such: {{ model.highlight_background }} {% if model.highlight_background %} Right now I have a method of doing this which feels incredibly hacky: I'm overriding the admin.AdminSite._build_app_dict to put 'highlight_background': model._meta.permissions, into model_dict and then adding permissions = (('highlight_background', 'Highlight Background'),) to the Meta class of the model I want this to occur on, and then calling using model.highlight_background.0.0 in the template. This "works", in that I am able to do exactly what I want with this information, but it doesn't seem like the "correct" way of doing it. What I would like to know is if there is a better way of going about doing this, preferably without overriding anything other than the admin site templates, or overriding as little as possible. I have since started going down the rabbit hole of overriding the django.db.models.options.Options.__init__ to add self.highlight_background = False and just directly utilize highlight_background = True in the Meta class, but I thought I had better ask if there is a proper way of going about this before I spend too much time … -
Dynamic Url Routing In Django not working
The page works fine without url routing but says page not found on url routing views.py urls.py post.html -
Virtual Environment: Django's db -> CommandError: You appear not to have the 'sqlite3' program installed or on your path
I'm looking for the solution to how can I run manage.py dbshell in a virtual environment without error: CommandError: You appear not to have the 'sqlite3' program installed or on your path. I have installed Python in venv. I added the path to environment variables. I can populate db in the Django project, so it's not a case of not working MySQL. Answers for similar questions somehow doesn't work in my case. Windows 10, python 3.x -
Filter by CharField pretending it is DateField in Django ORM/mySql
I am working with a already-done mySQL Database using Django ORM and I need to filter rows by date - if it wasn't that dates are not in Date type but normal Varchar(20) stored as dd/mm/yyyy hh:mm(:ss). With a free query I would transform the field into date and I would use > and < operators to filter the results but before doing this I was wondering whether Django ORM provides a more elegant way to do so without writing raw SQL queries. I look forward to any suggestion. Thank you. -
Django: Avoid race condition duplicates objects in complex relationship
I have two models, Company and Customer, that are related through an intermediate table, Contact. There should never be more than one Contact object that relates a Company object to a Customer object. The complexity is that the Company-Customer relationship is not a normal ManyToMany. Company and Contact are related with a ForeignKey, but Customer and Contact are related through a ManyToMany. Here are the simplified models. class Company(Model): # Unrelated fields class Customer(Model): # Unrelated fields class Contact(Model): company = ForeignKey(Company, related_name="contact") customer = ManyToMany(Customer, related_name="contact") # Unrelated fields When Customer data comes in related to a Company, I create a Customer or find an existing Customer with matching data. Then I create a Contact to link the Customer to the Company. This is the code I've been using to check whether a Contact already exists linking the Company and Customer: try: contact = customer.contact.get(company=company) except Contact.DoesNotExist: contact = customer.contact.create(company=company) But this allows for the occasional creation of duplicate Contacts due to race conditions. Using Django's built in get_or_create doesn't work here because of the M2M relationship between Customer and Contact. How can I enforce Contacts being unique connections between Companies and Customers while avoiding this race condition? --In … -
Log files isn't writable
I'm create a website based on Django with Docker. I've a problem whit the management of log files of Gunicorn. With the script below the site runs without problems: #!/usr/bin/env bash cd personal_website exec gunicorn personal_website.wsgi:application \ --name personal_website \ --bind 0.0.0.0:"${PROJECT_PORT}" \ --workers 3 \ "$@" Here what I see on terminal: dev_website | [2022-01-21 16:36:17 +0000] [1] [INFO] Starting gunicorn 20.1.0 dev_website | [2022-01-21 16:36:17 +0000] [1] [DEBUG] Arbiter booted dev_website | [2022-01-21 16:36:17 +0000] [1] [INFO] Listening at: http://0.0.0.0:8301 (1) dev_website | [2022-01-21 16:36:17 +0000] [1] [INFO] Using worker: sync dev_website | [2022-01-21 16:36:17 +0000] [11] [INFO] Booting worker with pid: 11 dev_website | [2022-01-21 16:36:17 +0000] [12] [INFO] Booting worker with pid: 12 dev_website | [2022-01-21 16:36:17 +0000] [13] [INFO] Booting worker with pid: 13 dev_website | [2022-01-21 16:36:17 +0000] [1] [DEBUG] 3 workers But when I add the logging files: #!/usr/bin/env bash # Prepare log files and start outputting logs to stdout touch ./logs/gunicorn.log touch ./logs/gunicorn-access.log cd personal_website exec gunicorn personal_website.wsgi:application \ --name personal_website \ --bind 0.0.0.0:"${PROJECT_PORT}" \ --workers 3 \ --log-level=debug \ --error-logfile=./logs/gunicorn.log \ --access-logfile=./logs/gunicorn-access.log \ "$@" I see the error below: dev_website | Error: Error: './logs/gunicorn.log' isn't writable [FileNotFoundError(2, 'No such file or … -
Getting user data from token in reactjs? Django Rest API
Can someone help me understand what I need to do to login users into my website and use their information throughout my react js program? I have watched all the videos I could find on django authentication and the majority of them end with you dealing with the user's access token, but where do you get their database stored information? I don't have it all setup correctly anymore but before I had it where whenever a user registered / login it creates the access token but where do I get information such as the current users name (things stored in the database)? So for example: In the Navbar I could have your username, image, etc. Would I have to pass these things back through a prop to app.js when you login? I think I saw and tried a get by token function, but I don't think it worked. I was using the default SQL Django comes with but I plan on / started using postgres after following a tutorial but I am not opposed to using anything. At this point I am trying to start over completely, but I can't find any tutorials that show what I am looking for … -
Is there a a function to implement when dealing with django image or filefield? Please help me out [closed]
This is the error that I am getting Os error function not implemented -
Django AgoraRTC
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'play') at joinAndDisplayLocalStream DevTools failed to load source map: Could not load content for http://127.0.0.1:8000/static/assets/AgoraRTC_N-production.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE -
django TimeStampedModel not auto adding time stamps in drf APITestCase
I have a model which inherits TimeStampedModel to auto-add created and modified fields. I have an API that takes post data and creates objects. Everything is working fine when I am testing the API with the postman. But when I am testing the API with DRF test cases then I am getting the error django.db.utils.IntegrityError: null value in column "created" violates not-null constraint DETAIL: Failing row contains (101, null, null, 3600, 3, 6). I am getting this error only when I call the API from test cases. Otherwise, this is working fine in the postman and react frontend. This is the model. class Activity(TimeStampedModel): time_spent = models.IntegerField() # in seconds activity_type = models.ForeignKey( ActivityType, on_delete=models.CASCADE, related_name='activities') user = models.ForeignKey('user.User', on_delete=models.CASCADE) This is the API. @action(detail=True, methods=['post'], serializer_class=ActivitySerializer, url_name='add_activity') def add_activity(self, request, pk): # add activity for a activity type activity_type = self.get_object() serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save(user=request.user, activity_type=activity_type) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And this is the Test Case. def test_add_activity_succeed(self): self.client.credentials(HTTP_AUTHORIZATION=f'Token {self.token}') data = {"time_spent": 3600} activity_type = ActivityType.objects.create(name="test1", user=self.user) response = self.client.post(reverse('activity_types-add_activity', kwargs={'pk': activity_type.id}), data=data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) I also have some other models which also inherit TimeStampedModel. And test cases are working fine while creating … -
How to investigate slow Heroku application
I deployed my first two applications on a free Heroku account, but the performance is terribly slow. Is it with my code? Do I need to upgrade my Heroku subscription? How do I investigate what's wrong? 1st App: Django Rest API for backend 2nd App: React for frontend -
Python set comprehension with multiple Django object fields
I have a queryset with many attributes and potentially 1000s of rows. I use set comprehension to identify unique attributes within the queryset in order to create dropdown filters that help users filter the objects in a table. Currently, I have created a set comprehension for each filtered attribute. Is there a more efficient way to obtain these unique attribute values? qs = Foo.objects.filter(criteria=unique_to_each_user) filter_name = sorted({q.name for q in qs if q.name}) filter_group = sorted({q.group for q in qs if q.group}) filter_origin = sorted({q.origin for q in qs if q.origin}) For a few attributes, I also create a tuple that contains total count along with each unique attribute: l_team = lambda x: x.team team_totals = {total: sum(1 for q in qs) for total, qs in groupby(sorted(qs, key=l_team), l_team)} filter_team = sorted({(q.team, team_totals.get(q.team)) for q in qs if q.team}) I use qs for other purposes, and was attempting to avoid several trips to the DB by performing the set comprehension actions on qs, as opposed to using a technique at the DB level, such as distinct - link. However, these set comprehensions are hurting performance. Perhaps I am misguided in minimizing DB queries above all else? Is there a better … -
Best way to generate a token with django
I have an app where the backend is in django rest framework. The frontend is in react. The app has two sets of apis. One set interacts with the react frontend (lets call them frontend apis). The other set are apis that the customer can directly use. (lets call them customer apis) The react frontend has a "Generate a new token". With this token, the user can begin using the customer apis. The token used with the customer apis will expire but the lifetime which can be set by the user in the frontend. How should I implement authentication for customer apis and frontend apis. -
Which is the best way to validate mutually exclusive fields in a Django Serializer?
I Have the following serializer: class MutuallyExclusiveSerializer(serializers.Serializer): field_a = serializers.Charfield() field_b = serializers.Charfield() field_c = serializers.Charfield() I want an scalable way to raise an error if the user send more than 1 of these fields that are mutually exclusive. I can make a custom validator but it is not easy to scale if more fields are added in the future. What is the recommended methodology in this case? Thanks in advance! -
Django webpack loader respecting STATICFILES_STORAGE setup
I have a Django project that uses webpack loader to work with vue with the following settings DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' So, for example, if we hav <script src="{% static "js/main.js" %}"></script>, Django will convert it, into, say, https://my_service_url.com/static/js/main.js That's fine. But the trouble starts with bundles generated by webpack loader, for which I have the following settings WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': False, 'BUNDLE_DIR_NAME': '/bundles/', # must end with slash 'STATS_FILE': os.path.join(FRONTEND_DIR, 'webpack-stats.json'), 'POLL_INTERVAL': 0.1, 'IGNORE': [r'.+\.hot-update.js', r'.+\.map'], } } And in my vue.config.js file const BundleTracker = require("webpack-bundle-tracker"); const pages = { ... } module.exports = { publicPath: '/static/', outputDir: './dist/', chainWebpack: config => { config.optimization .splitChunks(false) config .plugin('BundleTracker') .use(BundleTracker, [{filename: '../frontend/webpack-stats.json'}]) config.resolve.alias .set('__STATIC__', 'static') config.devServer .public('/static/') .host('0.0.0.0') .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .headers({"Access-Control-Allow-Origin": ["\*"]}) }, pages: pages }; So, the issue is that under this setup, Django tries to look up the bundles using the address http://localhost:8006/static/js/my_bundle.js instead of https://my_service_url.com/static/js/my_bundle.js How do I make this work ? I guess I have to adjust the module.exports somehow... -
django: use model methods without create instance
I have a Model Product with business methods. I can for instance run Product.simulation(). My model contains relationship with other Models. Let's say my Product is serialized as / can be created from: { "name": "productA", "items": [2,3,13], "dealer": [1,2] } I would like to be able to compute Product.simulation with those values without creating it. I have multiple signals and batch operation on Product Model I dont want to run on the only for simulation objects. I could create a for_simulation attribute on Product and specify on my signals / batch operation to don't run on those instances but it seems do lead to duplicate code and be forgotten on some signals / batch. On the other hand, I could rewrite all my methods in Product, Item, Dealer to work with dict as input but there's a lot of them. Is there a better way to achieve my goal ? Ideally I would like to be able to do something like: p = Product({ "name": "productA", "items": [2,3,13], "dealer": [1,2] }) p.simulation() I cannot: my instances need to be saved to build relationships. -
Force a Django QuerySet to not hit the db?
I'm trying to improve query performance by use of prefetch_related and select_related. My goal is to only make one database query for a particular operation. Currently the way I'm determining whether I achieved my goal (only make one query) is to watch the database logs. I'd like to that to be easier, and ideally enforce that future changes don't undo my work. Is there a way I can tell a QuerySet to not hit ever the database (raise an exception if it can't fulfill a request from the cache)? -
More efficient and effective queryset?
I have this models in my project: ... class User(AbstractBaseUser): ... income = models.BigIntegerField() ... class Credit(models.Model): ... user = models.ForeignKey(User, on_delete=models.PROTECT) cycle = models.CharField(choices=CYCLE_CHOICES, max_length=2) amount = models.BigIntegerField() ... I want a queryset that queries the database for a user whose income is greater than $10,000, and who has at least two(2) credits whose cycle is cycle_credited and amount is $30,000. Currently, I have the following querysets: ... user = get_object_or_404(User, id=id) is_eligible = False num_of_ten_k_credits = Credit.objects.filter(user=user, user__income__gt=10000, cycle=constants.cycle_credited, amount=30000).count() if num_of_ten_k_credits >= 2: is_eligible = True Is there a more efficient and effective way to do this? Like a one-liner solution with fewer DB calls?