Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'Department' object is not iterable in Django?
I coundn't find the mistakes here. Department's objects and Year's objects are already created inside admin panel. So the field department and years in ClassForm should be rendered as CharField with choices. Why when I submitted the form I got the error? class Department(models.Model): name = models.CharField(max_length=100) class Year(models.Model): department = models.ManyToManyField(Department) years = models.CharField(max_length=20) class Class(models.Model): teacher = models.ForeignKey("account.CustomUser", on_delete=models.CASCADE) department = models.ForeignKey(Department, on_delete=models.CASCADE) years = models.ForeignKey(Year, on_delete=models.CASCADE) subject = models.CharField(max_length=200, unique=True) # forms.py class ClassForm(forms.ModelForm): class Meta: model = Class fields = ['department', 'years', 'subject'] #view.py def createClassView(request): if request.method == "POST": form = app_forms.ClassForm(request.POST, instance=request.user) if form.is_valid(): form.save() return JsonResponse({'success': True}, status=200) else: return JsonResponse({'error': form.errors}, status=400) return HttpResponse("Class Create View") error I got Traceback (most recent call last): File "/Users/muongkimhong/Developments/itc-attendance/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/muongkimhong/Developments/itc-attendance/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/muongkimhong/Developments/itc-attendance/env/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/Users/muongkimhong/Developments/itc-attendance/attendance/app/views.py", line 63, in createClassView form.save() File "/Users/muongkimhong/Developments/itc-attendance/env/lib/python3.8/site-packages/django/forms/models.py", line 461, in save self._save_m2m() File "/Users/muongkimhong/Developments/itc-attendance/env/lib/python3.8/site-packages/django/forms/models.py", line 443, in _save_m2m f.save_form_data(self.instance, cleaned_data[f.name]) File "/Users/muongkimhong/Developments/itc-attendance/env/lib/python3.8/site-packages/django/db/models/fields/related.py", line 1670, in save_form_data getattr(instance, self.attname).set(data) File "/Users/muongkimhong/Developments/itc-attendance/env/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 992, in set objs = tuple(objs) TypeError: 'Department' object is not iterable -
How can I resolve the argument of type 'WindowsPath' is not iterable in django? not opening any pdf or csv files
'''Traceback (most recent call last): File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 196, in finish_response self.close() File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\site- packages\django\core\servers\basehttp.py", line 111, in close super().close() File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\wsgiref\simple_server.py", line 38, in close SimpleHandler.close(self) File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 334, in close self.result.close() File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\site- packages\django\http\response.py", line 252, in close signals.request_finished.send(sender=self._handler_class) File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\site- packages\django\dispatch\dispatcher.py", line 175, in send for receiver in self._live_receivers(sender) File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\site- packages\django\dispatch\dispatcher.py", line 175, in <listcomp> for receiver in self._live_receivers(sender) File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\site- packages\django\db\__init__.py", line 57, in close_old_connections conn.close_if_unusable_or_obsolete() File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\site- packages\django\db\backends\base\base.py", line 514, in close_if_unusable_or_obsolete self.close() File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\site- packages\django\db\backends\sqlite3\base.py", line 248, in close if not self.is_in_memory_db(): File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\site- packages\django\db\backends\sqlite3\base.py", line 367, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\site- packages\django\db\backends\sqlite3\creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'WindowsPath' is not iterable [24/Sep/2020 04:10:17] "GET / HTTP/1.1" 500 59 I tried almost all ways that are saved in this site even 10-year-old post tried. But still, the error remains the same. I am not using any file to open on python or on a web app but still facing this error. -
Cannot check multiple lines string in django
I actually want to check the answer from user is correct or incorrect. When I tried in dummy data with pure python code, it work properly. But, when I try to add it into django, it doesn't valid. I also tried 3 methods anyway, but still doesn't work. In my mind, perhaps because \n issue. class UserAnswerView(APIView): allowed_methods = ('post',) permission_classes = (permissions.AllowAny,) # just for test serializer_class = UserAnswerSerializer def validate_answer(self, exercise_id, user_answer): exercise = Exercise.objects.get_or_none(id=exercise_id) if exercise and user_answer: if isinstance(user_answer, str): correct_answers = exercise.answer_set.published() # [method 1] # return correct_answers.filter(Q(answer__icontains=user_answer)).exists() # [method 2] # for correct_answer in correct_answers: # if correct_answer.answer in user_answer: # return True # [method 3] return any(c.answer in user_answer for c in correct_answers) return False Here is the models.py; class Exercise(TimeStampedModel): id = models.BigAutoField(primary_key=True) title = models.CharField(_('Title'), max_length=200) order = models.PositiveIntegerField(_('Order'), default=1) course = models.ForeignKey(Course, on_delete=models.CASCADE) sort_description = models.TextField(_('Sort Description')) description = models.TextField(_('Description')) initial_script = models.TextField(_('Initial Script'), blank=True) objects = CustomManager() def __str__(self): return self.title class Answer(TimeStampedModel): id = models.BigAutoField(primary_key=True) exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE) answer = models.TextField(_('Answer'), help_text=_('The correct answer')) objects = CustomManager() def __str__(self): return self.answer[:50] In my test, I put this codes into the user_answer form and also correct_answer. from datetime … -
Change the text on Django Admin's "Add another SomeObject"-button when showing inlines
With the following code, I get a Django Admin UI, where I on the Person page can add a number of Measurement's. The link / button shows the text "Add another Measurement". How can I change that text? class Person(models.Model): class Meta: db_table = 'people' verbose_name = "Person" verbose_name_plural = "People" name = models.CharField(max_length=100, null=False, blank=False) class Measurement(models.Model): class Meta: db_table = 'measurements' verbose_name = "Measurement" verbose_name_plural = "Measurements" value = models.IntegerField(null=False) person = models.ForeignKey(Person, null=False, on_delete=CASCADE) class MeasurementInline(InlineModelAdmin): model = Measurement extra = 0 class PersonAdmin(admin.ModelAdmin): fields = ('name',) list_display = ('name',) inlines = [MeasurementInline] -
Convert into lower case while saving in database Django
I am adding few names in my database using the admin panel. How can I convert the the name string to lowercase before saving? -
How can I use select_related in case like this?
I have this models class Person(models.Model): name = models.CharField() ... class Names(models.Model): person = models.ForeignKey(Person) .... class Address(models.Model): person = models.ForeignKey(Person) .... class Occupation(models.Model): person = models.ForeignKey(Person) .... I want to fetch data by join all tables but i keep get error.. any help please? -
How to use related_query_name in GenericRelation as you would use related_name in ManyToManyField?
I am trying to implement a Django tagging system using a GenericRelation instead of a ManyToManyField. My Tag model is defined as follows: class Tag(models.Model): tag = models.SlugField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() tagged_object = GenericForeignKey() Since in my app I am tagging Definitions, my Definition model has a GenericRelation to the Tag model described above as follows: class Definition(models.Model): ... tags = GenericRelation(Tag, related_query_name="definition") Now, I am trying to query my database to get all the Definitions tagged with a certain Tag. If I used a ManyToManyField for tags in my Definition model and included a related_name of, say, "tag_definitions" I would have been able to achieve that like so: tag.tag_definitions.all() Because I am using GenericRelation, however, this is not possible. How can I achieve this using related_query_name? -
How to use different css for queryset objects?
I have different styles of heading in a 5- column layout newspaper template. I want to apply different css to the title of each column. The queryset is the {% block content %}How can I iterate over the queryset objects and apply different css to each {{ post.title }} variable? <div class="content"> <div class="collumns"> {% block content %} {% endblock %} </div> <div class="collumn"><div class="head"><span class="headline hl1">May the Force be with you</span><p><span class="headline hl2">Let go your conscious self and act on instinct</span></p> </div> -
AttributeError: 'set' object has no attribute 'items' in django
I am customizing in the DRF to give an error response value if a null value is entered in the body or title. However, after squeezing the code, the test results in the following error. AttributeError: 'set' object has no attribute 'items' I don't know what this error means, and I don't know why it happens. Can you tell me what the problem is in my code? Here's my code. views.py class CreatePostView (ModelViewSet) : serializer_class = PostSerializer permission_classes = [IsAuthenticated] queryset = Post.objects.all() serializers.py class PostSerializer (serializers.ModelSerializer) : author = serializers.CharField(source='author.username', read_only=True) title = serializers.CharField(allow_null=True) text = serializers.CharField(allow_null=True) image = ImageSerializer(many=True) class Meta: model = Post fields = ['pk', 'author', 'title', 'text', 'like', 'liker', 'image', 'view'] def validate (self, attrs) : title = attrs.get('title', '') text = attrs.get('text', '') error = {} if title is None and text is None : error['message'] = '제목과 본문을 넣어주세요.' raise serializers.ValidationError(error) if title is None : error['message'] = '제목을 넣어주세요.' raise serializers.ValidationError(error) if text is None : error['message'] = '본문을 넣어주세요.' raise serializers.ValidationError(error) return attrs def create (self, validated_data) : return Post.objects.create(**validated_data) -
Nuxt Axios works only during deploy
I've recently made a blog where I post things but I found one little problem. I'm using Nuxt With Axios as frontend and Django as backend hosted on heroku. The thing is, when I run the frontend on my localhost everything works like a charm. No error, no cors problem. Everything simply goes as expected until I deploy the frontend to Netlify. From there it goes weird. The Axios seems to work only during the deploy phase and doesn't update anything that goes afterwards. For Better image: Imagine your site is up With some Posts and you decide to put another post in Django. This post is simply ignored by the website and doesnt show up. There is also no error in the console. But once I redeploy the site, it magically loads it. Im really lost. If anyone knows how to solve this I'd be really grateful. Writing on phone so sorry for styling if it sucks. I'll post code later -
Django test without vpn
I want to test my function, where I add a new object to a database and then (still in this function) the object is being sent to a server. The problem is that to send the object to a server I need to run VPN. I'm wondering is there a way to run this function in my test, but skip the line responsible for sending the object to the server, or somehow simulate this behavior? Currently, I'm not able to run my test because I'm getting Failed to establish a new connection: [Errno 110] Connection timed out My test looks like this: def test_create_ticket_POST_adds_new_ticket(self): response = self.client.post(self.create_ticket_url, { 'title': 'test title', 'description': 'test description', 'grant_id': 'test grant id', }) result_title = Ticket.objects.filter(owner=self.user).order_by('-last_update').first().title result_count = Ticket.objects.filter(owner=self.user).count() self.assertEquals(response.status_code, 302) self.assertEquals(result_title, 'test title') self.assertEquals(result_count, 1) And the post request is calling this function: @login_required @transaction.atomic def create_ticket(request): if request.method == 'POST': ticket_form = TicketForm(request.POST) tags_form = TagsForm(request.POST) attachments = AttachmentForm(request.POST, request.FILES) if ticket_form.is_valid() and attachments.is_valid() and tags_form.is_valid(): jira = JIRA(server=JIRA_URL, basic_auth=(jira_user, jira_password)) new_issue = add_issue(request, jira, ticket_form) add_attachments(request, jira, new_issue) set_tags(request, new_issue, tags_form) messages.info(request, _(f"Ticket {new_issue} has been created.")) return redirect(f'/tickets/{new_issue}/') else: ticket_form = TicketForm() tags_form = TagsForm() attachments = AttachmentForm(request.POST, request.FILES) return … -
i want to add custom field in django-allauth SignupForm
i wanted to add custom field with django-allauth SingupForm and adding new field like phone number. i already managed to add this field in Postgresql on my own(without migrations,but by my hands). this is my postgresql screen In my signup page i have these fields already but i can't managed to add "phone" to my database, i really want to make it! please someone help me. forms.py from allauth.account.forms import SignupForm from django import forms class CustomSignupForm(SignupForm): first_name = forms.CharField(max_length=30, label='Voornaam') last_name = forms.CharField(max_length=30, label='Achternaam') phone = forms.CharField(max_length=30, label='phone') def __init__(self, *args, **kwargs): super(CustomSignupForm, self).__init__(*args, **kwargs) self.fields['first_name'] = forms.CharField(required=True) self.fields['last_name'] = forms.CharField(required=True) self.fields['phone'] = forms.CharField(required=True) def save(self, request): user = super(CustomSignupForm, self).save(request) user.phone = self.cleaned_data.get('phone') user.save() return user def signup(self,request,user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() return user settings.py ACCOUNT_FORMS = {'signup': 'registration.forms.CustomSignupForm'} -
SMTPAuthenticationError at /
Iam trying to send an email with my django app to my email. and its firing the above error. my Login credentials in my settings are correct and i have turned on less secure apps and DisplayUnlockCaptcha but it still persists. nvironment: Request Method: POST Request URL: http://localhost:8000/ Django Version: 3.0.9 Python Version: 3.8.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'shield_sec'] Installed 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'] Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/apple/projects/Django/ingabo_sec/shield_sec/views.py", line 17, in contact send_mail ( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/mail/__init__.py", line 60, in send_mail return mail.send() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 69, in open self.connection.login(self.username, self.password) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 734, in login raise last_exception File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 723, in login (code, resp) = self.auth( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 646, in auth raise SMTPAuthenticationError(code, resp) Exception Type: SMTPAuthenticationError at / Exception Value: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials 138sm1136246lfl.241 - gs settings.py STATIC_URL = '/static/' … -
how to filter spetember in datefield django?
Hope You Are Good I Have This Model: class Task(models.Model): .... timestamp = models.DateField(auto_now_add=True) now I want to get only September tasks not matter what date is, I want to filter or grep September 2020 tasks how can I achieve this? -
Django - import constants's variable from variable
I've a Django application and I'd like to import from myapp.constants the MYCONSTANT variable in a way that myapp and MYCONSTANT is stored in a variable: VAR1='myapp' VAR2='MYCONSTANT' and I'd like to import it using the variables. from VAR1.constants import VAR2 , but of course it does not work. How can I achieve this? Is there any similar way to using apps.get_model() ? -
Django in Google Cloud Run cant find /cloudsql socket
I have a dockerized django application which I've built, uploaded to GCR and then deployed as a google cloud run service. However, when starting up I get the following error (from the cloud run logs): psycopg2.OperationalError: could not connect to server: Connection refused Is the server running locally and accepting connections on Unix domain socket "/cloudsql/kingdoms-289503:us-west1:kingdomsdb/.s.PGSQL.5432"? My database settings for django look something like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': "/cloudsql/kingdoms-289503:us-west1:kingdomsdb", 'USER': "postgres", 'PASSWORD': "password", 'NAME': "postgres", } } And I've made sure to create the connection to the database From what I understand, cloud run is supposed to magically mount a at /cloudsql that django can use to connect to postgres, but the error implies that it's not being mounted. Is there an extra piece of configuration I would need to check to make sure that socket is there? Are there alternatives to connecting to cloudsql that don't involve this socket? -
How to Upload Djnago Project in Digitalocean?
i am Uploading Djnago project in Digitalocean server.i have uploaded all my files in Digitalocean.and i am Using MongoDb database.but when i run my project it showing below error raise ServerSelectionTimeoutError( pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 5f6c644e91288a299c34f17e, topology_type: Single, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [Errno 111] Connection refused')>]> This error is Related Mongodb database or Something else? i don't Know How to Upload Mongodb database in Digitalocean.can any one Explain step by step how to upload Django project in Digitalocean with Mongodb.i will be Thankful. -
Django adding field to ElasticSearch
I'm trying to add a field to a well established ElasticSearch (I would rather not do a rebuild) and I wonder if there is a way of simply adding the field. So if I have something as simple as @search_index.document class OrganisationDocument(Document): name = fields.TextField() class Django: model = Organisation queryset_pagination = 100 When I add a new field, for example: facilities_resident_transport = fields.NestedField(properties={ 'name':fields.KeywordField() }) I now get an error RequestError(400, 'search_phase_execution_exception', 'failed to create query: { I have tried saving an Organisation with the field used but when I look in Kibana the field isn't there. Can I populate without a complete rebuild? -
How to do a variation in Views.py for add to cart function
Views.py I just need to make the add to cart have variation like for example S,M,L This is not Django Rest Framework and this is model.py -
Element of type <myclass> is not json serializable
class priceManage(object): def __init__(self,uid): self.uid = uid def getRealPrice(self): tot_price = 0 plist = e_cart.objects.filter(e_uid_id = self.uid, e_ordnum__isnull = True).select_related() for x in plist: tot_price += x.e_prodid.getRealPrice()*x.e_qta return float(tot_price) all done, but when i instance object and try to serialize with json i get Object of kind priceManage is not json serializable why f i return a float? So many thanks in advance -
How do I create a Django endpoint that receives JSON files?
I'm designing a Django endpoint that is supposed to receive a JSON file message from an API that sends texts. On the API, I'm supposed to include the endpoint (drlEndpoint) so that after a text is sent, the app endpoint can also receive a report in form of a JSON file. How do I design an endpoint that can receive the report? Here is the API... api_key = "" api_secret = "" # Get Bearer token = api_key + api_secret message_bytes = token.encode('ascii') base64_bytes = base64.b64encode(message_bytes) bearer = base64_bytes.decode('ascii') # Handle data and send to API enpoint post_dict = { 'unique_ref': '', 'clientId': '', 'dlrEndpoint': '', 'productId': '', 'msisdn': '', 'message': '', } data = json.dumps(post_dict) # converts data to json url = '' # set url headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + bearer} # set headers r = requests.get(url=url, data=data, headers=headers) # make the request to the API endpoint my_data = r.json() # converts the request into json format print(my_data) # makes the request and prints to terminal -
Attribute Error in Django model Foreign Key
In My Django Project, there are two apps: Login and Company The error that am receiving in this is AttributeError: module 'login.models' has no attribute 'Country' Company App > models.py from django.db import models from login import models as LM class CompanyProfile(models.Model): full_name = models.CharField(max_length=255, unique = True) country = models.ForeignKey(LM.Country, on_delete=models.SET_NULL, null=True, blank=False) state = models.ForeignKey(LM.State, on_delete=models.SET_NULL, null=True, blank=False) def __str__(self): return self.full_name Login App > models.py class Country(models.Model): """List of Country""" name = models.CharField(max_length=50, unique= True, default='None') code = models.CharField(max_length=2, unique= True, primary_key=True, default ='NA') def __str__(self): return str(self.code) class State(models.Model): """List fo State""" region = models.CharField(max_length = 255, unique = True, primary_key=True, default='None') country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, blank=False, default ='NA') def __str__(self): return self.region Here is test to check that weather is login is getting imported or not def test_import(): try: # import pdb; pdb.set_trace() importlib.find_loader('LM.Country') found = True except ImportError: found = False print(found) Answer is received stands to be True python3 manage.py shell >>> test_import() True Now on other stackoverflow blogs i checked i thought it could be of Circlular Import But i have already fixed that still am getting this error? Thanks in Advance Regards -
Cron for sending emails after 3 days in django
I dont have any knowledge about the cron. In my project once the task is assigned to employee email is sent to his mailid. If the employee does not complete the task within deadline I want to send the mail after every 3 days to complete the task. Can anyone give me I idea what I should do. The project is on my local environment, does it support or I should take server. -
How to extract data from django model
There is a django model with this field task_args. This field contains record like this ('test_user', 1, ['test'], 'id_001'). This field is a text field. How do I filter data from this model using this field I tried the following but this does not seem to work user = request.user.username num = 1 parsed_data = eval("['test']") id = "id_001" print(type(parsed_data)) args = f"{(user,num,parsed_data,id)}" print(args) task_id = list(TaskResult.objects.filter(task_args=args).values('task_id')) This results in an empty list. -
Convert nested query MySQL django
Im trying to convert this query from MySQL to Django, but I don't know how to do nested select in python, please, could you help me? SELECT zet.zone, SUM(CASE WHEN zet.`status` = 'available' THEN zet.total ELSE 0 END) AS `ge_available`, SUM(CASE WHEN zet.`status` = 'assigned' THEN zet.total ELSE 0 END) AS `ge_assigned`, SUM(CASE WHEN zet.`status` = 'on_going' THEN zet.total ELSE 0 END) AS `ge_on_going`, SUM(CASE WHEN zet.`status` = 'stopped' THEN zet.total ELSE 0 END) AS `ge_stopped` FROM (SELECT vhgz.zone zone, vhgz.status status, COUNT(*) total FROM view_historic_group_zone vhgz, (SELECT group_id gid, MAX(date_change) fe FROM historical_group WHERE date_change <= '2020-09-21 15:12:56' GROUP BY group_id) hg WHERE vhgz.date = hg.Fe AND vhgz.gid = hg.gid GROUP BY vhgz.zone, vhgz.status) zet GROUP BY zet.zone Model.py class viewhistoricgroupzone (models.Model): zone = models.CharField(max_length=50) date = models.DateTimeField() status = models.CharField(max_length=23, blank=True, null=True) gid = models.PositiveIntegerField() The result should be: {"zone":"Spain","available":0,"assigned":1,"on_going":15,"stopped":2} {"zone":"England","available":12,"assigned":4,"on_going":5,"stopped":1} {"zone":"Italy","available":2,"assigned":4,"on_going":12,"stopped":4} {"zone":"Germany","available":5,"assigned":8,"on_going":7,"stopped":3}