Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get value list from ManytoMany Queryset
I have two models Bookings and Presenter, which are setup as a Many to Many Field. I then have a function called 'export excel' (found on online tutorial) , which exports all of the data from the Booking model to an Excel spreadsheet. Each booking may contain more than one presenter. Currently the export works but displays a new record for bookings that have more than one presenter assigned. Is it possible to get the presenter name be displayed as a list? rather than duplicating the booking on a new row. So for example if booking 1 contains two presenters the names will display as ['mark', 'jake'] Queryset used in export excel function rows= Bookings.objects.all().exclude(status='Cancelled').values_list( 'id', 'program_type', 'delivery_method', 'booking_date', 'booking_time', 'duration', 'school_name', 'year_level', 'street', 'suburb', 'post_code', 'contact_name', 'email', 'phone_number', 'comments', 'students_attending', 'status', 'presenter__name') Models class Presenter(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=80) email = models.EmailField() phone_number = models.CharField(max_length=10) role = models.CharField(max_length=50) def __str__(self): return self.name class Bookings(models.Model): statuses = [ ('TBC', 'TBC'), ('Confirmed', 'Confirmed'), ('Completed', 'Completed'), ('Cancelled', 'Cancelled'), ] id = models.BigAutoField(primary_key=True) program_type = models.CharField(max_length=40) delivery_method = models.CharField(max_length=40) booking_date = models.DateField() booking_time = models.CharField(max_length=10) duration = models.CharField(max_length=10) school_name = models.CharField(max_length=120) year_level = models.CharField(max_length=10) street = models.CharField(max_length=120) suburb = models.CharField(max_length=120) post_code … -
How do I display objects by day in Django template?
Right now, I have a few logs in my database that I want to display them by date in the Django template. How do I do it? This is how my current system looks like.. How I want them to look like.. JUNE 20, 2022 ------------- Nice songs! I'm listening to Massive Attack right now - 03:06 AM Just completed a sketch of the LOG IT! - 21:48 PM I'm watching a movie right now. It's called Black Swan - 21:30 PM Just had a pizza from Pagliacci! - 21:25 PM models.py class Logs(models.Model): log = models.CharField(max_length=100) created = models.DateTimeField(auto_now=False, auto_now_add=True) -
Context attributes not available in Django template
I'm trying to display a specific attribute in a template in Django. I believe I've passed the correct queryset in the context, but for some reason I'm only able to access the id attribute, and not the title attribute that I need. Views.py: @login_required def watchlist_view(request): listings = models.WatchedListing.objects.filter(owner = request.user) return render(request, "auctions/watchlist.html", {"listings": listings}) @login_required def add_to_watchlist(request, listing_id): listing = models.Listing.objects.get(pk=listing_id) user = request.user currently_watched = models.WatchedListing.objects.filter(owner = request.user) if listing in currently_watched.all(): messages.error(request, "This item is already on your watchlist.") return redirect(reverse('listing', args=[listing.pk])) else: watchlist = WatchedListing() watchlist.owner = user watchlist.watched_listing = listing watchlist.save() messages.success(request, "Added to your watchlist!") return redirect(reverse('listing', args=[listing.pk])) Models.py: class Listing(models.Model): title = models.CharField(max_length=64) description = models.TextField() start_bid = models.ForeignKey(Bid, on_delete=models.CASCADE, related_name="start_bid") image_url = models.TextField(null=True) category = models.CharField(max_length=64, null=True) current_bid = models.ForeignKey(Bid, on_delete=models.CASCADE, related_name="current_bid") is_active = models.BooleanField() owner = models.ForeignKey(User, on_delete=models.CASCADE) num_bids = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) class WatchedListing(models.Model): watched_listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name='watched_listings', blank=True, null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name ='watchlist_owner') watchlist.html: {% extends "auctions/layout.html" %} {% block title %} Watchlist {% endblock %} {% block body %} {% if messages %} {% for message in messages %} <strong style="color: red">{{ message }}</strong> {% endfor %} {% endif %} {% if listings … -
How can I make carousel Flex Message in Line Bot with Django?
I know how to show carousel message with using carousel template, however ,it can't show in Line when using computer. So I want to try not to use carousel template, I have seen these code for carousel Flex Message in JSON ,how can I switch these code to Django format? { "type": "carousel", "contents": [ { "type": "bubble", "body": { "type": "box", "layout": "vertical", "contents": [ { "type": "text", "text": "First bubble" } ] } }, { "type": "bubble", "body": { "type": "box", "layout": "vertical", "contents": [ { "type": "text", "text": "Second bubble" } ] } } ] } -
Django, AWS Elastic Beanstalk
Hope everyone is doing well. I'm trying to deploy a Django APP to elastic beanstalk however it is failing. The error is Following services are not running: web I'm not sure how to resolve it, I changed settings to be allowed_hosts = ['*'] but this still came up with the error. I'm concerned it may be the database connection? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '***', 'USER': '***', 'PASSWORD': '***', 'HOST': '***.***.ap-southeast-2.rds.amazonaws.com', 'PORT': '5432', } } Any help will be much appreciated I've googled and googled and tried and tried but no solutions have worked for me (works fine with manage.py runserver). The logs have not been much help to me as I don't understand them that well. When I attempt to connect I get this in the nginx logs. 4335#4335: *88 connect() failed (111: Connection refused) while connecting to upstream The daemon.log have these warnings: WARN -- : log file "/var/log/nginx/healthd/application.log.2022-06-20-01" does not exist The engine.log has these warnings: [WARN] Warning: process healthd is already registered... Deregistering the process ... [WARN] stopProcess Warning: process xray is not registered [WARN] deregisterProcess Warning: process httpd is not registered, skipping... (Note: This is my first time using AWS EB) -
How to create a custom migration to change the inbuilt django User model
I am having this problem in creating a custom User model in django and i actually posted this question before and I did get an answer from "@Sorin Burghiu" and it was very helpful since I did not even know the issue before but now I do know the issue but I don't know how to write my custom migration to do so let me post the answer here "Changing the user model mid-project is a difficult situation if you are trying to override the existing user model with a NewUser. Reference You will need to write a custom migration to do it to transfer all data from the current User table to the NewUser table, then drop the User table safely. If that's not the case and you just started the project, feel free to drop your current database and make migrations again after changing the default user model in settings.py (you are doing that already). Also make sure all imports in other files are undated to use your NewUser model instead of the django default User." This is the answer but I don't know how to write a migration for this and this is where i need some … -
"This field is required" error for FormSet when requesting payload, but works fine with Form
Need some help with this. If I pass a formset to a html template and request its payload with a POST request, I get this error Field Error: primary <ul class="errorlist"><li>This field is required.</li></ul> Field Error: symbol <ul class="errorlist"><li>This field is required.</li></ul> Field Error: secondary <ul class="errorlist"><li>This field is required.</li></ul> For the formset, the forms are dynamically added or deleted onto the page, but there will always be a single form on the page when the page is loaded. And for the other dynamically added forms, they get the same error as well. But when I pass a single form to the html template, I get the POST payload just fine. views.py def advanced(request): form = formset_factory(Search) if request.method == 'POST': formset = Search(request.POST) for field in formset: print("Field Error:", field.name, field.errors) return render(request,"advancedsearch.html", {"formset":form}) forms.py indicator = [ ('', ''), ('high', 'Estimated high'), ('low', 'Estimated low'), ('median', 'Estimated median'), ('realprice', 'Real Price'), ] symbol= [ ('', ''), ('>', 'higher than'), ('<', 'less than'), ('=', 'equal to'), ] class Search(forms.Form): primary = forms.CharField(label='a', widget=forms.Select(choices=indicator)) symbol = forms.CharField(label='b', widget=forms.Select(choices=symbol)) secondary = forms.CharField(label='c', widget=forms.Select(choices=indicator)) advancedsearch.html <form method="POST" action="">{% csrf_token %} {% for x in formset %} <div class = "d-flex flex-row justify-content-center … -
Add instead of replace Django
Why does this view replace what is in the addedauction instead of adding another listing? I would like to create a Watchlist in which the user can add an auction to its Watchlist after clicking on the link, but when i checked how it works it after adding one auction the next one simply replaces the first one. How do I put multiple auctions on a user's Watchlist? views.py def addtowatchlist(request, auctionurl): try: currentauction = get_object_or_404(Auctionmodel, id=auctionurl) print(currentauction) user_list, created = Watchlist.objects.get_or_create(owner=request.user) user_list.addedauction.add(currentauction) return HttpResponseRedirect(reverse("watchlist")) except TypeError: return HttpResponseRedirect(reverse("index")) models.py class Watchlist(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, related_name="ownerofwatchlist") addedauction = models.ManyToManyField(Auctionmodel, blank=True, related_name="auctionadd") -
Next Vercel frontend, how to connect to Elastic Beanstalk Django backend?
My Next frontend is already hosted on Vercel. How do I shoot my apis to my backend? I already have a django app running on elastic beanstalk but its health is in red condition and also its debug mode is set to True. I tried shooting postman APIs locally, it works with http://127.0.0.1:8000. but it doesn't with http://my-eb-site:8000 . How do I configure my elastic beanstalk django backend for production? Also how would i face CORS issue later on? -
If Operational error happens in django query in read database router, rerun the query on write database
When a read query from read_db() fails due to following error ERROR: cancelling statement due to conflict with recovery Detail: User query might have needed to see row versions that must be removed how to catch the error and rerun the same query on a write db. -
My code in terminal in vs code is disabled how to enable?
How to enable running script in visual studio in windows 11? When I'm running visual studio code terminal is said that my running script is disabled how can I fix it? -
How to redirect to url instead of error message? "Direct assignment to the forward side of a many-to-many set is prohibited."
I wish if the object exists in the database the user would just be redirected to "watchlist" instead I get the error "Direct assignment to the forward side of a many-to-many set is prohibited. Use addedauction.set () instead.". def addtowatchlist(request, auctionurl): Watchlist.objects.get_or_create(owner=request.user, addedauction=auctionurl) if Watchlist.objects.get_or_create(owner=request.user, addedauction=auctionurl) == False: return redirect("watchlist") return redirect("watchlist") -
How can I do this same thing using DRF OrderingFilter?
I am hoping to order a model by a DateTimeField using the DRF OrderingFilter. I am able to do this manually but not with the DRF backend. I have the following ModelViewSet: class DropTemplateViewSet(viewsets.ModelViewSet): serializer_class = DropTemplateSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ["status"] def get_queryset(self): qs = DropTemplate.objects.annotate(start_time=F("collectiontemplates__visible_start_time")).filter(author__id=self.kwargs["author_pk"]).distinct("id") if "ordering" in self.request.query_params: return drop_templates.order_by("author_droptemplate.id", f"{self.request.query_params['ordering']}") else: return drop_templates I am using the distinct("id") because this Annotated QuerySet contains DropTemplates in the response. How can I achieve the same thing with the OrderingFilter? When I attempt to do this with the following ModelViewSet: class DropTemplateViewSet(viewsets.ModelViewSet): serializer_class = DropTemplateSerializer filter_backends = [DjangoFilterBackend, OrderingFilter] filterset_fields = ["status"] ordering_fields = ["title", "start_time"] ordering = ["start_time"] def get_queryset(self): return DropTemplate.objects.annotate(start_time=F("collectiontemplates__visible_start_time")).filter(publisher__id=self.kwargs["publisher_pk"]).distinct("id") I get this error: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT COUNT(*) FROM (SELECT DISTINCT ON ("publisher_droptem... ^ ) -
Gunicorn: UndefinedTable: relation "user" does not exist
Here is the scenario, I'm deploying the Django app on an ec2 instance. I'm following this guide Digitalocean deployment guide. when I run my app using python manange.py runserver 0.0.0.0:800 and access the admin portal via http://server-ip-address:8000. everything works fine. But when I run gunicorn --bind 0.0.0.0:8000 myproject.wsgi and try to access the admin page it gives me 500 server errors and exception: UndefinedTable: relation "user" does not exist LINE 1: ...r", "user"."is_staff", "user"."is_superuser" FROM "user" WHE... Setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework_simplejwt.token_blacklist', 'rest_framework_simplejwt', 'corsheaders', 'drf_yasg', 'django_extensions', 'src', 'communications', 'rest_framework', 'registration', ] 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', # 'django.contrib.auth.middleware.AuthenticationMiddleware', ] WSGI_APPLICATION = 'apbackend.wsgi.application' AUTH_USER_MODEL = 'registration.User' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], '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', ], }, }, ] 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', }, ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.IsAdminUser' ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication', ), } registration.models.py from django.db import models # Create your models here. import uuid from django.db import models from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import … -
Selenium webdriver.Remote() can't click on elements
Situation I'm using the Selenium Remote webdriver to do my tests on a Django project. I have several Docker containers, which is why I needed to use the Remote driver. Problem Thing is, the Selenium and Django project containers are connected properly and I am able to perform tests, but whenever I try the click() method on any element, I get the error Element <...> could not be scrolled into view However, by searching around I found out that doing self.driver.execute_script("arguments[0].click();", element) instead does work. I've read somewhere that it might be a problem that some part of the website is not loaded yet when Selenium attempts to click(), but that still doesn't tell me what to do. Any ideas? -
Django TestCase Delete without passing the article number in URL but as a value submit
How to delete article object in Django TestCase without passing it in URL delete/1/ im using <form action="{% url 'delete' %}" method="POST"> {% csrf_token %} <button class="btn btn-danger" type="submit" name="article_id" value="{{ article.pk }}"> Delete </button> </form> urls.py path('delete/', views.delete, name='delete'), views.py @login_required(login_url='/login') def delete(request): article_to_delete = get_object_or_404( Article, id=request.POST.get('article_id')) if request.method == "POST" and request.user.is_authenticated: article_to_delete.delete() messages.success( request, ('Your article was successfully deleted!')) else: messages.warning( request, ('Something went wrong!')) return HttpResponseRedirect(reverse_lazy("home")) and my test_views.py def test_delete(self): self.client.login(username='mark', password='12345') I would like to make some good comparison for example self.assertEqual(response.status_code, 200) -
How can I Implement withdraw amount from investment balance using Django?
Here is my Model I have spent countless hours trying to implement "withdraw from investment" without success. print(investment.investment_return) shows the exact amount is being deducted but I don't know why its not updating total_available_balance from the dashboard. This is where I want the money to be deducted from total_available_balance = Investment.objects.filter(is_active=False).aggregate( total_available_balance=Sum('investment_return'))['total_available_balance'] from django.db import models from django.db.models import Max, Sum, F from datetime import datetime, timedelta class Investment(models.Model): PLAN_CHOICES = ( ("Basic - Daily 2% for 180 Days", "Basic - Daily 2% for 180 Days"), ("Premium - Daily 4% for 360 Days", "Premium - Daily 4% for 360 Days"), ) plan = models.CharField(max_length=100, choices=PLAN_CHOICES, null=True) deposit_amount = models.IntegerField(default=0, null=True) basic_interest = models.IntegerField(default=0, null=True) premium_interest = models.IntegerField(default=0, null=True) investment_return = models.IntegerField(default=0, null=True) withdraw_amount = models.IntegerField(default=0, null=True, blank=True) balance = models.IntegerField(default=0, null=True, blank=True) total_available_balance = models.IntegerField(default=0, null=True, blank=True) locked_balance = models.IntegerField(default=0, null=True, blank=True) investment_id = models.CharField(max_length=10, null=True, blank=True) is_active = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now=True, null=True) due_date = models.DateTimeField(null=True) def save(self, *args, **kwargs): if self.plan == "Basic - Daily 2% for 180 Days": self.basic_interest = self.deposit_amount * 365 * 0.02/2 self.investment_return = self.deposit_amount + self.basic_interest self.due_date = datetime.now() + timedelta(seconds=5) else: self.premium_interest = self.deposit_amount*365*0.04 self.investment_return = self.deposit_amount +self.premium_interest self.due_date = datetime.now() + … -
Can't open file font error in xhtml2pdf template - django
style type="text/css"> @font-face {font-family: RTLFont; src: url('F:\MyProjects\my_app\app\static\app\fonts\font_name.ttf')} // Here body { font-weight: 200; font-size: 14px; font-family: RTLFont; } @page { size: a4 portrait; @frame header_frame { /* Static Frame */ -pdf-frame-content: header_content; left: 50pt; width: 512pt; top: 50pt; height: 40pt; } @frame content_frame { /* Content Frame */ left: 50pt; width: 512pt; top: 90pt; height: 632pt; } @frame footer_frame { /* Another static Frame */ -pdf-frame-content: footer_content; left: 50pt; width: 512pt; top: 772pt; height: 20pt; } } .text-header-primary { color: red; } getting me an error: TTFError at /api/visits/print Can't open file "C:\Users\User~1\AppData\Local\Temp\tmptiuhy3pp.ttf" -
best way to solve this use case in django ORM
I have a usecase that there is a user table and a skill table . 1 user can have multiple skills , for example writing , scalping , coding etc upto 50 so what is best way to save this ? from my search I came to conclusion that ManyToMany field is best here like this class Skill(models.Model): name = models.CharField(max_length=50) class User(models.Model): skills = models.ManyToManyField(Skill, blank=True, null=True) but while getting data I have to reverse queries aswell like getting all users having a specific skill for example writing . I am go on right way or not . please any help would be highly appreciated -
Does a using `.exists()` on a queryset with `.annotate()` runs the annotations?
So, I have this queryset where I run pretty heavy annotations , but I need to also check whether any data exists or not. So if I run exists() would the annotations be evaluated too? -
Data Analytics website using Django Python
I want to create a python project that uses mysql for database, django for the webframe. The website will contain a bunch of graphs fetched via different REST APIs and will create plots for the given data. I will be using docker to install all the dependencies (cython, numpy, pandas, matplotlib etc.) . Matplotlib will create the plots to be forwarded to the django website. The website will automatically update itself periodically as more data comes in over time (gathers new data from the APIs once a week maybe). To access the data the user will have to login with user credentials(login and password). Only a handful of people will be able to access the website so it is not dedicated to have a lot of traffic. I will be using Bluehost to host my django website in the end. I have never worked with web frames before would this be a hard task to accomplish. Are there easier ways to implement this? Open to any suggestions. Any problems I might face whilst developing ? -
why in redirecting url changes in the console but not in the browser (django)?
When redirecting the url in the console changes but not in the browser view.py def tables(request): if request.method == 'POST': text = request.POST.get('data_table') table_to_file(text) return redirect(reverse('result')) else: matrix = Matrix.objects.all() context = {'matrix': matrix} return render(request, 'methods/tables.html', context) def result(request): return render(request, 'methods/result.html') urls.py urlpatterns =[ path('result/', result, name = 'result'), path('tables/', tables, name='tables'), In console [20/Jun/2022 00:22:17] "POST /methods/tables/ HTTP/1.1" 302 0 [20/Jun/2022 00:22:17] "GET /methods/result/ HTTP/1.1" 200 571 But nothing changes in the browser -
Getting this error while trying to set SendGrid's email API with Django - AttributeError: 'str' object has no attribute 'get'
I am attempting to set up SendGrid with Django so that my website can send automated emails through SendGrid. So far, I haven't been able to send any emails. My settings are configured like this: EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_BACKEND = 'sgbackend.SendGridBackend' EMAIL_HOST_USER = 'apikey' # this is exactly the value 'apikey' with open(os.path.join(BASE_DIR, 'SENDGRID_API_KEY.txt')) as f: SENDGRID_API_KEY = f.read().strip() EMAIL_HOST_PASSWORD = SENDGRID_API_KEY EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'dac@projectado.com' SENDGRID_SANDBOX_MODE_IN_DEBUG=True I'm attempting to run this code to send an email: message = Mail( from_email='dac@projectado.com', to_email='taylor.ryanc@gmail.com', subject='Sending with Twilio SendGrid is Fun', content='test123') try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e.message) And I'm getting this error: 2022-06-19 15:42:18,726: Internal Server Error: /register/ Traceback (most recent call last): File "/home/ryanctaylor/.virtualenvs/cts-virtualenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/ryanctaylor/.virtualenvs/cts-virtualenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/ryanctaylor/.virtualenvs/cts-virtualenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ryanctaylor/CTS/Registration/views.py", line 173, in register_view message = Mail( File "/home/ryanctaylor/.virtualenvs/cts-virtualenv/lib/python3.8/site-packages/sendgrid/helpers/mail/mail.py", line 31, in __init__ personalization.add_to(to_email) File "/home/ryanctaylor/.virtualenvs/cts-virtualenv/lib/python3.8/site-packages/sendgrid/helpers/mail/mail.py", line 319, in add_to self.tos.append(email.get()) AttributeError: 'str' object has no attribute 'get' Anyone know what I could be doing wrong here? Any help would be greatly appreciated. -
How can I Annotate() either by a related model @property OR with a reverse relation?
I have the following models: class DropTemplate(TimeStampedModel): author = models.ForeignKey(Author, on_delete=models.PROTECT) @property def start_time(self) -> Union[None, str]: earliest_collection = ( self.collectiontemplates.filter(drop_template_id=self.id, visible_start_time__isnull=False) .only("visible_start_time") .order_by("visible_start_time") .first() ) if earliest_collection is None: return None else: return earliest_collection.visible_start_time class CollectionTemplate(TimeStampedModel): drop_template = models.ForeignKey( DropTemplate, related_name="collectiontemplates", on_delete=models.PROTECT ) visible_start_time = models.DateTimeField(null=True, blank=True) And the following Django Rest Framework ModelViewSet: class DropTemplateViewSet(viewsets.ModelViewSet): serializer_class = DropTemplateSerializer filter_backends = [DjangoFilterBackend, OrderingFilter] ordering_fields = ["start_time"] ordering = ["start_time"] def get_queryset(self): return DropTemplate.objects.annotate(start_time= # <-- WHAT DO I INPUT HERE? ).filter(author__id=self.kwargs["author_pk"]) I have already attempted to put a Subquery() in the get_queryset method since it seems I cannot directly utilize the @property since it is not on the DB layer.: def get_queryset(self): collection_templates = CollectionTemplate.objects.filter(visible_start_time__isnull=False).only("visible_start_time") return DropTemplate.objects.annotate(start_time=Subquery(collection_templates, output_field=DateTimeField())).filter(author__id=self.kwargs["author_pk"]) However, I get the following error: subquery must return only one column I'm new to Django Query Aggregation and have spent too much time trying to figure this out on my own. I'm hoping someone here can provide some guidance. Thank you! -
Django Queryset return None instead 0
I have a queryset in Django: puntos_jornalero1 = Equipo.objects.filter( jlg1__puntos__etapa=2 ).annotate( puntos_jornalero1=Sum('jlg1__puntos__puntos', default=0) ) If I make the queryset without the filter, I get 0 or the Sum correctly, but if I want to have the filter but in this case, when the result is 0, I get None. I need 0 because after that I need to Sum again the results.