Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: AND filter on related objects
Imagine: class Player(model.Model): name = models.CharField() class Game(model.Model): name = models.CharField() class Match(model.Model): game = models.ForeignKey(Game, related_name='matches') class Score(model.Model): match = models.ForeignKey(Match, related_name='scores') player = models.ForeignKey(Player, related_name='scores') I'd like a query that returns all Match objects that contain a list of players. I'm really quite stuck. Say I have a list of Player objects (a QuerySet or a list of PKs, is fine), I can get all the matches ANY player played in as follows: Match.objects.filter(scores__player__in=players) But a list of matches that ALL players played in is eluding me. I'm wondering if there is a canonical approach to this, it is a simple AND query on related set of objects. I want matches where player[1] is in scores AND player[2] is in scores etc. Ultimately I want a list of games but I think that is easy from a list of matches: Game.objects.filter(matches__in=matches) I have considered ArrayAgg but it's both Postgresql specific and I've not found a syntax for filtering on membership. I have looked at Subquery but also not found a syntax that helps me here yet. There are also performance issues. Ideas I'm toying with are: Annotate a Match query with an ArrayAgg of Player objects that are … -
PGAdmin4 virtual host not working with Apache2 + WSGI
I have a problem. I'm creating a server where I will host a Django project and also PGAdmin4. I configured PGAdmin to run through apache2 and WSGI with a Python 3.8 virtual environment. It was working perfectly before I set up the Django project. at the ip/pgadmin. As soon as i manage to host the Django on the virtual host. The pgadmin started not to work. When trying to enter the "ip/pgadmin" while the django webserver is not at the root at the WSGIScriptAlias i receive this page. Not Found The requested URL was not found on this server. Apache/2.4.41 (Ubuntu) Server at 192.168.0.10 Port 80 and the following log error. The pgadmin4 is installed withing the same virtualenv that runs the django project but as they are daemons thats not a problem. So i do not see why is searching under "/var/www/acas_webserver/pgadmin/" [Tue Mar 16 00:54:22.633470 2021] [core:info] [pid 26119:tid 140348751849216] [client 192.168.0.5:63072] AH00128: File does not exist: /var/www/acas_webserver/pgadmin/ But when i place the django project at the root of the WSGIScriptAlias i reacieve this page but no log info to know what happened. Not Found The requested resource was not found on this server. I'm trying to get … -
Creating database cursor for SQL Server 2000 in Django throws ProgrammingError: SYSDATETIME Is Not A Recognized Function Name
I have to hook a modern Django application up to a very old version of SQL Server 2000. I don't need to be creating/inserting/selecting records; I just need to pass XML to a stored procedure. I've created an entry in the settings.py file for the SQL Server instance I must connect to. I'm getting weird behavior in the interactive shell when I try to create a cursor. Weirdly, the first time I create the cursor, Django throws an error. The second time, the cursor creates successfully and I can execute my stored procedure. django.db import connections cursor = connections['sqlServer2000'].cursor() File "/Users/qotsa42/lib/python3.8/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/Users/qotsa42/lib/python3.8/site-packages/django/db/backends/base/base.py", line 196, in connect self.init_connection_state() File "/Users/qotsa42/lib/python3.8/site-packages/sql_server/pyodbc/base.py", line 362, in init_connection_state val = cursor.execute('SELECT SYSDATETIME()').fetchone()[0] File "/Users/qotsa42/lib/python3.8/site-packages/sql_server/pyodbc/base.py", line 546, in execute return self.cursor.execute(sql, params) pyodbc.ProgrammingError: ('42000', "[42000] [FreeTDS][SQL Server]'SYSDATETIME' is not a recognized function name. (195) (SQLExecDirectW)") Weirdly, when I try to create the cursor again, it works and i have no issues. >>> from django.db import connections >>> cursor = connections['sqlServer2000'].cursor() File "/Users/qotsa42/lib/python3.8/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/Users/qotsa42/lib/python3.8/site-packages/django/db/backends/base/base.py", line 196, in connect self.init_connection_state() File "/Users/qotsa42/lib/python3.8/site-packages/sql_server/pyodbc/base.py", line 362, in init_connection_state val = cursor.execute('SELECT SYSDATETIME()').fetchone()[0] File "/Users/qotsa42/lib/python3.8/site-packages/sql_server/pyodbc/base.py", line 546, in execute … -
Accessing BASE_DIR in utils.py
I want to access an Excel file in my static folder from my myapp/utils.py. I'm getting an error when trying to bring in BASE_DIR from settings.py AttributeError: module 'django.conf.global_settings' has no attribute 'BASE_DIR' utils.py from django.conf import settings wb = openpyxl.load_workbook(os.path.join(settings.BASE_DIR, '/static/myfile.xlsx'), data_only=True) -
Why is pytest fails to assert the following django serializer?
I am using pytest and it has failed in two serializers that are not behaving as expected. This is my code for the models.py file: from django.db import models from django.contrib.auth.models import User import django.utils.timezone class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="client") birthDate = models.DateField(default=django.utils.timezone.now) phone_number = models.CharField(max_length=30) address = models.CharField(max_length=300) def __str__(self): return self.user.username class Contract(models.Model): client = models.ForeignKey( Client, on_delete=models.CASCADE, related_name="contracts", related_query_name="client", ) experation_date = models.DateField(default=django.utils.timezone.now) tacit_renewal = models.DateField(default=django.utils.timezone.now) I have tested the models and they are working as I expect them to. Now, I created three serializers, only the first one 'User', worked as I expected. The two others kept failing, the code is in test_serializers.py file: from rest_framework import serializers from .models import Contract, Client from .models import User as UserModel class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UserModel fields = ("username", "email", "first_name", "last_name") # Used in a Customer domain class ClientSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer(many=True) def to_representation(self, instance): representation = super().to_representation(instance) return { "id": instance.id, "username": instance.user.username, "email": instance.user.email, "first_name": instance.user.first_name, "last_name": instance.user.last_name, "birthDate": instance.birthDate, "phone_number": instance.phone_number, "address": instance.address, } class Meta: model = Client fields = ( "id", "user", "birthDate", "phone_number", "address", ) class ContractSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Contract fields = ("id", "url", "client", … -
Style errorlist in all Django forms?
This answer shows styling the Django errorlist for one form by passing it in the constructor, as described in the Django documentation. How can I style all forms in Django with the DivErrorList style given in that answer? -
Optimize a Django queryset to check if nested attribute is true and preserve order?
I have two models in Django, Course, which can have zero or more Classes. A class is basically a course but with a string start_date and a boolean honors field. I want to query for all courses that have at least one honors class, how would I do that? Second question is given a Course, I want to: query all other courses that have the same string subject field query all other courses that have the same string teacher field unique courses only (no duplicates) Courses with at least one honors Class The caveat is that I need to maintain priority so that all courses with a matching subject are earlier in the returned JSON than the course with a matching field. -
Problems to send email using Django EmailBackend
I don´t know what is wrong in my code. I´m trying to use send_mail using django.core.mail.backends.smtp.EmailBackend but is not working. The security level of my gmail account is unlocked and the message in python looks like sent the email message. But the email didn´t arrive in my email account. Bellow are the codes that I´m using. settings.py # Email configuration EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = '<my_email>@gmail.com' EMAIL_HOST_PASSWORD = '<my_password>' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_USE_SSL = False views.py In the top of file ... # send email from django.core.mail import send_mail ... In the request page def contact_us(request): if request.method == 'POST': form = ContactFormEN(request.POST) if form.is_valid(): sender_name = form.cleaned_data['name'] sender_email = form.cleaned_data['email'] message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['message']) send_mail('New Message from site', message, sender_email, ['<my_email>@gmail.com'], fail_silently=False) return render(request, 'contact_us.html') After run the code the console shows the follow message Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: New Message from site From: <from_email>@gmail.com To: <my_email>@gmail.com Date: Mon, 15 Mar 2021 23:01:50 -0000 Message-ID: <161584931042.10464.14254641113919007176@my_machine_name> Name has sent you a new message: Test message ------------------------------------------------------------------------------- -
Django model filtering from multiple tables without direct relation
Hey I have two tables "Book" and "Author" and they don't have a direct relation between each other but I need all the Book records whos author_id is in a list of ids from the table Author which is filtered according to the LIKE operator. The following SQL statement is exactly what I want to achieve with the django filtering options but it doesn't seem to work. I read a lot about select_related and prefetch_related but they don't seem to solve my problem because those tables don't have a foreign key to each other: SELECT * FROM Book b WHERE b.author_id IN (SELECT id FROM Author WHERE country LIKE "%er%") // this will give back a list of ids -
Error deploying to Elastic Beanstalk: chown /var/app/staging/bin/python: no such file or directory
I am trying to deploy my app to Elastic Beanstalk however the CLI keeps returning the following error when I run 'eb deploy'. I am puzzled because my app is running fine locally. What does the error mean and how can I resolve it? I have been trying to find answers for hours with no luck .. error 2021/03/15 22:49:08.925837 [INFO] Executing instruction: StageApplication 2021/03/15 22:49:09.877646 [INFO] extracting /opt/elasticbeanstalk/deployment/app_source_bundle to /var/app/staging/ 2021/03/15 22:49:09.877695 [INFO] Running command /bin/sh -c /usr/bin/unzip -q -o /opt/elasticbeanstalk/deployment/app_source_bundle -d /var/app/staging/ 2021/03/15 22:49:18.870026 [INFO] finished extracting /opt/elasticbeanstalk/deployment/app_source_bundle to /var/app/staging/ successfully 2021/03/15 22:49:18.872859 [ERROR] An error occurred during execution of command [app-deploy] - [StageApplication]. Stop running the command. Error: chown /var/app/staging/bin/python: no such file or directory -
Makemigrations: ValueError: <function ManyToManyField.contribute_to_class.<locals>.resolve_through_model
I struggle with migrations. I have created a model fine, with a model named 'RecipeIngredient', run migration and all is good. I decide to rename it to 'Ingredient', and change the only two places in models.py where it is mentioned: class Recipe(models.Model): created_by = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True, default=1) fooditems = models.ManyToManyField(Fooditem, through='Ingredient', through_fields=('recipe', 'foodit'), ) recipe_name = models.CharField(max_length=50, default='Calories') class Ingredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) foodit = models.ForeignKey(Fooditem, on_delete=models.CASCADE) q_set = models.DecimalField(max_digits=5, decimal_places=1, default=1) When i makemigrations, I have the error: ValueError: <function ManyToManyField.contribute_to_class.<locals>.resolve_through_model at 0x000001B1FDE8B550> contains a lazy reference to Fityfeed.recipeingredient, but app 'Fityfeed' doesn't provide model 'recipeingredient'. I would like to understand the logic in migrations: I can see that in the old migrations there is still a 'RecipeIngredient' of course , am I supposed to change /delete old migrations? That creates all sort of problems. Or maybe the cause is somewhere else, where could the old name be present in the project? Thanks a lot for your help D -
NoReverseMatch at / error when implementing a comment option
I'm trying to implement a comment option for a django social media app and I get the NoReverseMatch at / error. NoReverseMatch at / Reverse for 'post-detail' with arguments '(10,)' not found. 1 pattern(s) tried: ['post/int:pk/$'] I have read What is a NoReverseMatch error, and how do I fix it? and I understand that it seems like it can't find the url for post_detail.html. I have looked up a lot of similar issues but I can't find anything helpful to my case. I am following this tutorial : https://towardsdatascience.com/build-a-social-media-website-with-django-feed-app-backend-part-4-d82facfa7b3 I have tried to change the way I declare my url in urls.py but nothing seems to work so far. I am including the relevent python and html files , edited for length. urls.py from django.conf.urls import url, include from myapp import views as core_views from django.contrib.auth.views import LoginView, LogoutView from django.contrib import admin urlpatterns = [ url(r'^$', core_views.PostListView.as_view(), name ='home'), url(r'^post/<int:pk>/$', core_views.post_detail, name='post-detail'] views.py ... @login_required def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) user = request.user is_liked = Like.objects.filter(user=user, post=post) if request.method == 'POST': form = NewCommentForm(request.POST) if form.is_valid(): data = form.save(commit=False) data.post = post data.username = user data.save() return redirect('post-detail', pk=pk) else: form = NewCommentForm() return render(request, 'feed/post_detail.html',{'post':post, 'is_liked':is_liked, … -
How to deploy a Django project generated by Cookie cutter to Elastic Beanstalk?
So I'm following a book named Django Crash Course by the Greenfelds. Here's the starter template they used. https://github.com/feldroy/django-crash-starter So this project template generates a Django version of 3.1.1 with Python 3.8. I tried to use Amazon Linux and Amazon Linux 2 on generating an environment on Elastic Beanstalk, both had 502 Bad gateway error. I have no idea how to fix since I'm still learning. I'm curious how can I use this template for production ready to Elastic Beanstalk. Thanks! -
Django forms & document.getElementById javascript - doesn't find id?
I have an app with a draggable marker on a map which populates the latitude and longitude. Beforehand, I was using a normal form where each input has an ID, this meant I could use document.getElementById('someformID').value to get the coordinates of the marker and input them into the form. However, when using Django forms, each form element doesn't have an ID in the HTML, so instead I added it the forms.py file as an attribute. It now doesn't grab the coordinates however. In the below code, I'm looking to get latcentre1 and longcentre1 from the Javascript forms.py class SafezoneForm(forms.ModelForm): class Meta: model = Safezone name = forms.CharField(widget=forms.TextInput (attrs={'id': 'name'})) useremail = forms.CharField(widget=forms.TextInput (attrs={'id': 'useremail'})) latitudecentre = forms.CharField(widget=forms.TextInput (attrs={'id': 'latcentre1'})) longitudecentre = forms.CharField(widget=forms.TextInput (attrs={'id': 'longcentre1'})) fields = ['useremail', 'name', 'longitudecentre', 'latitudecentre'] labels = { "name": "Name of safezone", "useremail": "Alert Email", "latitudecentre": "Latitude", "longitudecentre": "Longitude", } From reference in HTML file <form action="" method="POST"> {% csrf_token %} {{form.as_p}} <input class="btn btn-primary" type="submit" name="Submit"> </form> Javascript in the HTML file marker.on('dragend', function() { var lngLat = marker.getLngLat(); var latforform = lngLat.lat; var lonforform = lngLat.lng; document.getElementById('latcentre1').value = lngLat.lat; document.getElementById('longcentre1').value = lngLat.lng; Thanks! -
Can I use annotate to create a Charfield in django?
I'm working with a dataset of objects called Account that needs to go through an annotate in order to make some calculations. I have a list of ranges [[0, 1], [2, 4], [5, 49], [50, 99]] that represent different ranges of employees. I want to make an annotate that analizes if an object account belongs to a certain range and if it does, create a dynamic field called "range_name" and store the range as a string. For some reason, when i want to do this I get this: django.core.exceptions.FieldError: Cannot resolve keyword '[0, 1]' into field. Choices are: annual_revenue, avg_deal_size, cltv, employees, velocity Here is my models.py: class Account(models.Model): name = models.CharField(max_length=200, null=True, blank=True) employees = models.PositiveIntegerField( db_index=True, blank=True, null=True, ) annual_revenue = models.BigIntegerField( db_index=True, null=True, blank=True ) avg_deal_size = models.PositiveIntegerField( db_index=True, null=True, blank=True ) cltv = models.BigIntegerField(db_index=True, null=True, blank=True) velocity = models.PositiveIntegerField( db_index=True, null=True, blank=True ) Here's the code from my views.py where I try the annotate(): accounts = Account.objects.all() employees_ranges = [[0, 1], [2, 4], [5, 49], [50, 99]] for employee_range in employees_ranges: #here i turn the range into a string ranges_as_string = ', '.join([str(number) for number in employee_range]) ranges_as_string = '['+ranges_as_string+']' accounts_with_range_field = accounts.filter(employees__range=var).annotate( range_name=Case( When( Q(employees__gt=var[0]) … -
How do I properly validate a ModelForm (best practices)?
I have a ModelForm that I need to validate. I am currently overriding clean() method with custom validator functions. These validators raise a ValidationError in case something is wrong. If everything is fine - they do nothing. I have two questions: Is this approach a good practice? I am naming my validator functions the following way: ensure_SOMETHING (e.g. ensure_circular_reference_nonexistence(...), ensure_max_depth_limit_is_respected(...), etc.). Again, is this a good practice? I haven't seen others user "ensure" in their function names. To be 100% clear, this is how my clean() method looks like: def clean(self, *args, **kwargs): ensure_circular_reference_nonexistence(...) ensure_max_depth_limit_is_respected(...) return super(MyForm, self).clean(*args, **kwargs) -
How to convert a string to valid json?
Is there an easy way to convert a string such as 'username=andrew&password=password1234' to { "username: "andrew", "password": "password1234" } ? I have been trying to loop through the string and manually add it but I was curious to see if there was an easier way or a library i'm just not seeing. -
How to make queries directly on the models.py file in django, to fill the fileds with the results?
Hi I want to know If I am able to work directly with queries inside the "models.py" file to make results the default values of some fields. For example: class NewModel(models.Model): Seats = models.IntegerField(default=<some_result_of_a_query>) ... Thanks! :) -
How to overwrite the `.create` method in writable nested serializer for nested models having ManyToMany Field?
I am trying to build an endpoint using Django Rest Framework for the Device model:- Device Model class AbstractDevice(OrgMixin, BaseModel): name = models.CharField() mac_address = models.CharField() key = KeyField() model = models.CharField() os = models.CharField() system = models.CharField() notes = models.TextField(blank=True, help_text=_('internal notes')) last_ip = models.GenericIPAddressField() management_ip = models.GenericIPAddressField() hardware_id = models.CharField() Config Model class AbstractConfig(BaseConfig): device = models.OneToOneField(Device, on_delete=models.CASCADE) templates = SortedManyToManyField() vpn = models.ManyToManyField() STATUS = Choices('modified', 'applied', 'error') status = StatusField() context = JSONField() For the above models, I have created serializers as:- DeviceConfigSerializer class DeviceConfigSerializer(serializers.ModelSerializer): class Meta: model = Config fields = ['backend', 'status', 'templates', 'context', 'config'] DeviceListSerilaizer class DeviceListSerializer(serializers.ModelSerializer): config = DeviceConfigSerializer() class Meta(BaseMeta): model = Device fields = ['id','name','organization','mac_address','key','last_ip', 'management_ip','model','os','system','notes','config'] def create(self, validated_data): import ipdb; ipdb.set_trace() config_data = validated_data.pop('config') device = Device.objects.create(**validated_data) Config.objects.create(device=device, **config_data) return device Since I want to incorporate a nested serializer and to make it writable It is required to manually add the .create or .update method. and the views: Views class DeviceListCreateView(ListCreateAPIView): serializer_class = DeviceListSerializer queryset = Device.objects.all() I am having a templates field which is a SortedManyToManyField() Field, if I am not wrong then I think something has to be tweaked with that field because when I am trying … -
Allow user to download file and then redirect to other page
I have a function like: def download(requests): with open(file_path2, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path2) return response #it stop executing here as we return. os.remove(file_path2) return render(request, 'user/charts.html', {'res': 'The file has decrypted'}) So what the function needs to do is, start the file downloading and after download delete the file from system then redirect to other page. But the problem is,for implementing downloading functionality , I use return and then it stops, So how can I execute next statements ? -
How to reset the values of form using the Ajax .reset() method every time the item is added in the cart in django
** I have tried many times, used query 2, 3 and even cdn but the reset function isn't working, firstly in jqyuery 2 it was showing the error like .reset() isn't a function, but in cdn or latest query 3 the error is not appearing, but the reset is also not working ** $(document).on('submit','#addCartForm',function(e){ {#var frm = $('#addCartForm');#} e.preventDefault(); $.ajax({ type: 'POST', url: '/cart_add', {#data: frm.serialize(),#} data: { project_id: $('#project_id').val(), amount: $('#amount').val(), project_category_id: $('#project_category_id').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success: function () { alert("Cart Added"); $("#addCartForm")[0].reset(); {#$("#addCartForm").empty();#} {#$('#addCartForm').trigger('reset');#} {#document.getElementById("addCartForm").reset();#} {#document.getElementById("addCartForm").reset(); {# THIS reset() FUNCTION IS USED TO RESET THE VALUES INSIDE THE FORM INPUT FIELDS: #} }, error: function () { alert("Something went wrong!"); }, }); }); ** I have to add the item in the cart one by one, but it isn't moving to the next item, it still have the first item's data. it adds the same data even I trigger an other item. I searched a lot but it isn't working. ** My Template {% for project in projects %} <form class="donate-page-form" id="addCartForm"> {% csrf_token %} <h4 class="text-uppercase our-causes__title text-truncate" id="logoColor"><a href="{% url 'project-detail' project.id %}">{{ project.get_name }}</a></h4> <p>{% if project.isZakat %}{% trans "Calculate your Zakat" %}{% else %}{% trans … -
Adding User model to the StructBlock class
I'm trying to create a simple blog page with image,content,date posted and user who posted. But I don't think that wagtail allows me to put in the user model into my block. class HomePage(Page): template_name = 'home/home_page.html' max_count = 1 subtitle = models.CharField(max_length=200) content = StreamField( [ ("title_and_text_block", AnnouncementBlock()) ] ) content_panels = Page.content_panels + [ FieldPanel("subtitle"), StreamFieldPanel("content") ] def get_context(self, request, *args, **kwargs): context = super().get_context(request, args, kwargs) context['posts'] = HomePage.objects.live().public() return context; from wagtail.core import blocks from wagtail.images.blocks import ImageChooserBlock class AnnouncementBlock(blocks.StructBlock): title = blocks.CharBlock(required=True, help_text='Add your title') content = blocks.RichTextBlock(required=True, features=["bold", "italic", "link"]) image_thumbnail = ImageChooserBlock(required=False, help_text='Announcement Thumbnail') class Meta: template = "streams/title_and_text_block.html" icon = "edit" label = "Announcement" My goal is everytime user posted a new announcement his/her name should appear. not sure how i can do that since in the block i cannot add the User model so that the user's detail will be saved along with the content/image etc. something like this. from wagtail.core import blocks from wagtail.images.blocks import ImageChooserBlock from django.conf import settings class AnnouncementBlock(blocks.StructBlock): title = blocks.CharBlock(required=True, help_text='Add your title') content = blocks.RichTextBlock(required=True, features=["bold", "italic", "link"]) image_thumbnail = ImageChooserBlock(required=False, help_text='Announcement Thumbnail') #USER is not allowed here. error on the model user = … -
How to migrate a Django model into models with table inheritance
Our current Django project has a model that already has a huge amount of instances in the database. When we started the project we had only one application in mind. Due to new requirements and planning for upcoming applications, we have realized that it might be very beneficial to restructure the database using model inheritance now before it's too late. This is because we can split this model (that has a lot of data in the database) into a base model and another one inheriting from it. The benefit of doing so is that the new applications of the project will also be able to inherit this base model as it contains common fields. I know that this change would imply a table for the base model and other tables that are related to that table. I am wondering if there's a way that I can perform these changes while minimizing the impact of the data. Ideally, I would like to keep the id's intact, since customers are using the data already. Since basically all the database is of ModelA, my idea was to convert all the data of this model into a model inheriting from a base model: ModelA(BaseModel) … -
I am Unable to find what's wrong with Heroku Deployment
I have Deployed a Django Application On HEROKU (Using HEROKU free Services). At the start, it was working well but now some of my product images are not showing up. Anyone can tell me what's wrong with this or why it's happening :( -
Code cleanup for Django queries and ternary operator
How best can I clean up this code into one Django query with the ternary operator : if isinstance(self.instance, Business): agg_shares = BeneficialOwnerShares.objects.filter( parent_company=parent ).exclude( owner_company=self.instance ).aggregate( sum_shares=Coalesce(Sum('allocation_of_shares'), V(0)) ) else: agg_shares = BeneficialOwnerShares.objects.filter( parent_company=parent ).exclude( owner_person=self.instance ).aggregate( sum_shares=Coalesce(Sum('allocation_of_shares'), V(0)) ) Am trying to add the ternary operator in the exclude() function to switch between the owner_person=self.instance and owner_company=self.instance, but it doesn't work , how best can I do this ?