Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Implementing a PostgreSql query with Django
Imagine a model in Django like: class MyModel(models.Model): data = JSONField() . . . The data is stored like this: {'1':'value1', '2':'value2', '3':'value3', ...}. The data keys are ['1', '2', '3', ...]. The query aim is to count the number of MyModels which have ids like '1' or '2' in data keys. The PostgreSql query is like: SELECT jsonb_object_keys(data) AS keys, COUNT(*) AS number FROM MyModel WHERE data ?| array['1','2'] GROUP BY keys The result is: keys | number -----+------- '1' | 150 '2' | 300 This means there are 150 MyModels that have '1' in their data keys and 300 MyModels with '2' in data keys. Now the question is how to implement the query with Django? -
DIfference Between two dates in django queryset
models.py class Operations(models.Model): model = models.CharField(max_length=100) process_status = models.CharField(max_length=100) created_date = models.DateField(null=True) views.py from django.db.models import DurationField, ExpressionWrapper, F from datetime import date today = date.today() created_queryset=Operations.objects.filter(process_status__startswith='Created').values('model').aggregate(days_awaiting=ExpressionWrapper(F('created_date')-F(today.strftime("%Y-%m-%d")),output_field=DurationField())).order_by('-created_date') I need output in no of days from today to the 'created_date' (Date format from Mysql database is in 2016-08-20) -
After i have installed allauth for django ModuleNotFoundError while migrating
I have installed django-allauth by pip install django-allauth. movies is the name of my app error image -
How to redirect to an explicitly named url in Django?
I am trying to have a redirect to a specific page base on a variable in my views.py: redirect(f'feed/user/{first_user}') But by having it like this it redirects me to the url: feed/search/feed/user/first_user instead I would like to redirect to the url feed/user/first_user I know that the feed/search/ part is appended because the search url in my urls.py calls the function that should redirect but I would like to keep it that way and only change the redirect. -
when click the send button showing full html source code in django
i just created a django form, once click the send button showing full html codes under the form. but message sent successfully. can you tell me how to resolve the issueenter image description here -
Refactoring multiple if conditions with Q() chaining in querystring evaluation Python/Django
I am working on cloning airbnb room registration system in Django. I have a class based view (HTTP get method) that filters rooms stored in the database according to various query string key value options and returns those rooms. Filter options provided through query string are: location = request.GET.get('location') adults = int(request.GET.get('adults', 0)) children = int(request.GET.get('children', 0)) infants = request.GET.get('infants', 0) min_cost = float(request.GET.get('min_cost', 0)) max_cost = float(request.GET.get('max_cost', sys.maxsize)) property_type = request.GET.get('property_type', None) place_type = request.GET.get('place_type', None) check_in = request.GET.get('checkin', None) check_in_date = datetime.datetime.strptime(check_in, '%Y-%m-%d') if check_in else None check_out = request.GET.get('checkout', None) check_out_date = datetime.datetime.strptime(check_out, '%Y-%m-%d') if check_out else None min_beds = request.GET.get('min_beds', None) min_bedrooms = request.GET.get('min_bedrooms', None) min_baths = request.GET.get('min_baths', None) amenities = request.GET.getlist('amenities', None) languages = request.GET.getlist('languages', None) I decided to store all filter expressions as Q() objects using &= operation. Rooms with already booked dates and host-chosen unavailable dates ('blockeddate') that are in conflict with provided check_in_date and check_out_date will be filtered out. After storing all Q() expression in a variable called 'queries', I passed 'queries' as an argument to Room.objects.filter() function. 'min_beds', 'min_bedrooms', and 'min_baths' options were evaluated after initial filtering so that I could perform annotate() function on the filtered queryset. Following code works, … -
Trying to filter data based on start and end date
I am using django filter package to filter data based on start, end date and class of dues fields defined in my models. The problem is If I select only class_of_fields data is filtered but when I select start and end_date along with class_of_dues no data is filtered below are my codes models.py class DuesLevy(models.Model): class_of_dues = models.CharField(max_length=30, default=options.CHOOSE, choices=options.CLASS_OF_DUES, blank=True) payment_circle = models.CharField(max_length=30, default=options.CHOOSE, choices=options.PAYMENT_CIRCLE) payment_option = models.CharField(max_length=30, default=options.CHOOSE, choices=options.PAYMENT_OPTION) amount = models.DecimalField(max_digits=8, decimal_places=2) transaction_id = models.CharField(max_length=30, null=True, blank=True, editable=False, default=my_rand) payment_channel = models.CharField(max_length=30, default=options.CHOOSE, choices=options.PAYMENT_CHANNEL_TYPE) payment_date = models.DateField() start_date = models.DateField() end_date = models.DateField() date_recorded = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) description = models.TextField(blank=True, null=True) def __str__(self): return self.amount filter.py from .models import DuesLevy, User from django_filters import widgets import django_filters from django import forms from django_select2 import forms as s2forms from backend import options class DuesFilter(django_filters.FilterSet): class_of_dues = django_filters.CharFilter( widget=s2forms.Select2Widget(choices=options.CLASS_OF_DUES, attrs={'class':'form-control'})) start_date = django_filters.DateFilter(field_name='payment_date', widget=forms.DateInput(attrs={'class':'form-control', 'type':'date'}), lookup_expr='lt',label='Start Date') end_date = django_filters.DateFilter(field_name='payment_date', widget=forms.DateInput(attrs={'class':'form-control', 'type':'date'}), lookup_expr='gt',label='End Date') user = django_filters.ModelChoiceFilter(queryset=User.objects.all(), widget=s2forms.ModelSelect2Widget( attrs={'class': 'form-control'}, model=User, search_fields=['member_id__icontains'], )) class Meta(): model = DuesLevy fields = ('class_of_dues', 'start_date', 'end_date') views.py class ListMemberDues(LoginRequiredMixin, View): login_url = '/backoffice/' def get(self, request): queryset = DuesLevy.objects.filter(user=request.user) query_filter = DuesFilter(request.GET, queryset) context = { 'form':query_filter.form, 'query':query_filter, } … -
How would I customize my form for uploading images?
I was wondering if someone know why my field for uploading pictures is like this? I can't select new pictures from my computer to upload, only ones already uploaded in the model instances through my Admin panel. It looks this way on my all of my routes. Here is link for my github repository - https://github.com/eonbre/DogApi1/tree/master/DrWebTestProject I would also love if someone would help me to return a random image on my /breeds//random route. enter image description here -
Python app returns MySQL data 3 times instead of 1
I have a simple MySQL table with the following meta and content +--------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | Name | varchar(100) | YES | | NULL | | | School | varchar(45) | YES | | NULL | | +--------+--------------+------+-----+---------+----------------+ +----+---------+--------+ | id | Name | School | +----+---------+--------+ | 1 | Artem | AU | | 2 | Simon | AAU | | 3 | Steffen | AU | +----+---------+--------+ from which I'm trying to fetch all data using a simple python app, however my output is returned like this when I run the app(click to enlarge photo): but what I expect it to return is (1, 'Artem', 'AU'), (2, 'Simon', 'AAU'), (3, 'Steffen', 'AU') only. The Python code is import MySQLdb from django.shortcuts import render from django.http import HttpResponse def getFromDB(): data = [] db = MySQLdb.connect(host="ip", user="user", passwd="pw", db="db") cur = db.cursor() cur.execute("SELECT * FROM students") students = cur.fetchall() for student in students: data.append(students) return data def index(request): return HttpResponse(getFromDB()) What am I missing? -
Django Pedigree Table
I am in the process of creating a site with Django for my wife and her dog club. I've seen many projects in php but none in python. I'm up for tackling this in any direction! I am wanting to dynamically create a table like this: My model looks like such (simplified for the question): class Dogs(models.Model): did = models.IntegerField(blank=true, null=true) name = models.TextField(db_column='name', blank=true, null=true) sire = models.TextField(db_column='Sire', blank=true, null=true) dam = models.TextField(db_column='Dam', blank=true, null=true) I've created a few different recursive functions that do correctly determine the ancestors of a child, but I am having difficulty outputting in a meaningful manner. Example: dog = [] def pedigree(did, max): con = sqlite3.connect('dog.sqlite3') con.row_factory cursor = con.execute('SELECT "Call Name", ROUND(((JulianDay("now") - JulianDay("Date of Birth"))/365.25),1), "Sex" FROM dogs where did IS %s ' % did).fetchall() for row in cursor: name, age, gender = row[0], row[1], row[2] sql = "SELECT a.Sire, a.Dam, s.'Registered Name', d.'Registered Name' FROM dogs a INNER JOIN dogs s ON a.Sire = s.did INNER JOIN dogs d ON a.Dam = d.did WHERE a.did = " printTree(sql, did, name, 0, max) return dog def printTree(stmt, did, name, N, max): rspan = 2**(max-N) if (rspan > 1): #print('rowspan= ', rspan, name) … -
django login form returns 'AnonymousUser' object has no attribute '_meta'
I am working on a django web app. In this web app, I have a login page. But when I use the click the login button, I get the following error message 'AnonymousUser' object has no attribute '_meta' I tried looking for this online and found these links in StackOverflow. link1 and link2. But the answers provided in these links do not seem to be working for me. This is my code so far views.py def login_page(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) user = form.get_user() login(request, user) if form.is_valid(): return redirect('global:homepage') else: form = AuthenticationForm() return render(request, 'accounts/login.html', {'form': form}) login.html <form class="" action="{% url 'accounts:login' %}" method="post"> {% csrf_token %} {% for field in form %} <p> <div class="form-group"> {% render_field field class="form-control" placeholder=field.label %} {% if field.help_text %} <p class="help-block"><small>{{ field.help_text }}</small></p> {% endif %} </div> {% for error in field.errors %} <p style="color: red">{{ error|add_class:'text-danger' }}</p> {% endfor %} </p> {% endfor %} <button type="submit" class="btn btn-primary btn-block btn-lg mt-5">Log in</button> </form> Not sure what I am doing wrong or what the error message means -
Operand data type nvarchar is invalid for sum operator
I tried to sum the data from my database using below code. models.py class Income(models.Model): Total= models.CharField(max_length=512,null =True,blank=True) views.py : Total_income = Income.objects.filter(Q(title='Salary')| Q(title='Bonus')).aggregate(Sum('Total')) But I got this error when I try to run it. ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Operand data type nvarchar is invalid for sum operator. (8117) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)') I'm new to Python and Django so I really appreciate your help on this. -
Custom user can't login
I have created a custom user model for 'dealers' and 'staff'. After creating a 'dealer' model I cannot login. I have tried both my 'accounts/login' form as well as the /admin page. When I try to login it says `Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive. accounts/models.py from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin, ) # Create your models here. class UserManager(BaseUserManager): def create_user(self, email, first_name, last_name, company, phone, is_active=True, is_admin=False, is_staff=False, is_dealer=False, password=None): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have a password") if not first_name: raise ValueError("Users must have a first name") if not last_name: raise ValueError("Users must have a last name") if not company: raise ValueError("Users must have a company") if not phone: raise ValueError("Users must have a phone number") user_obj = self.model( email = self.normalize_email(email) ) user_obj.set_password(password) user_obj.first_name = first_name user_obj.last_name = last_name user_obj.company = company user_obj.phone = phone user_obj.admin = is_admin user_obj.staff = is_staff user_obj.dealer = is_dealer user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_superuser(self, email, first_name, last_name, company, phone, password=None): user = self.create_user( email, first_name, last_name, company, phone, password=password, is_admin=True, … -
Django admin refresh table data without reloading full page
I am customizing admin interface. I want to refresh table data instead of refreshing full page. I am able to add the refresh button but don't know how to achieve refresh table data. This is what I have got so far. Thanks in advance. -
Unable to receive form data from Frontend using React/Django
I have been working on Pinterest-like app where users can upload pins along with a picture. After crafting "FileView", which is the API that uploads a received file onto S3 and provide the Frontend with the resulting URL for the picture, I have tested with Postman successfully. Below are my views.py code snippet and the screenshot of Postman request. views.py class FileView(View): s3_client = boto3.client( 's3', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_ACCESS_KEY ) @login_required def post(self, request, **kwargs): user = kwargs['user'] user_id = kwargs['user_id'] name = request.POST.get('title') paragraph1 = request.POST.get('text', None) board = request.POST.get('board', 1) board = Board.objects.get(id=board) print(request.FILES) if request.FILES == None: return JsonResponse({"message": "REQUEST FILES IS EMPTY"}, status=406) file = request.FILES['filename'] self.s3_client.upload_fileobj( file, "pinterrorist", file.name, ExtraArgs={ "ContentType": file.content_type } ) image_url = S3URL+file.name image_url = image_url.replace(" ", "+") new_pin = Pin.objects.create( image_url = image_url, name = name, paragraph1 = paragraph1, board = board ) new_pin.user.add(user) new_pin = model_to_dict(new_pin, fields=["image_url", "name", "paragraph1", "board"]) return JsonResponse({"new_pin": new_pin}) However, when I try to work it out with the frontend, the request does not go through the views.py. It goes through the decorator, which means there is nothing wrong with the header's authorization token. I searched online to find ways to fix this but one of … -
read only attribute is safe in django forms?
Setting read only attrs for django forms is safe?. In my django projects I do something like this: def someUpdateView(request): form = EmployeeForm(instance=Employeem.objects.get(pk=1)) return render... class EmployeeForm(forms.ModelForm) declaring here read only attrs field by widgets dict in Meta class or in init method (i.e. pk fields or other fields like email for keeping inmutable). But what if an user opens web browser inspector mode and edits html field value or deletes read only attribute? during form.save() django will save the new value even it was read only (from html) and if this happens, there is a way to handle that?. -
Why Does My Deploy Directory Keep Changing
Sorry if this is a really dumb question, I am just starting out with AWS. I am using ElasticBeanstalk to deploy a Django app. The first time I deployed the code the path to the code was /var/app/staging later I noticed it had changed to /var/app/current. It seems to changes back and forth after some but not all deploys. How can I either programmatically determine the path or make it be the same path every time? As you can imagine, this situation makes running manage commands impossible if your don't know that path. -
Populate Highcharts Pie Chart with JSON Data for Django Application
The HighCharts pie chart displays an empty chart after loading.enter image description here Here is my views.py @login_required def update_appscan(request, proj_value='proj', ver_value=v.get_version()): graph_data = c.get_appscan_graph(proj_value, ver_value) return render(request, 'jinja2/appscan/appscan.html', 'dataset' : graph_data) In graph_data, I have my data something like this. {'category': ['High', 'Medium', 'Low'], 'issues': [0, 4, 8]} I want to categorize the data as High, Medium, Low in Pie chart with their values respectively. and in appscan.html <script> Highcharts.chart('container', { chart: { plotBackgroundColor: null, plotBorderWidth: null, plotShadow: false, type: 'pie' }, title: { text: 'Appscan Vulnerabilities, 2020' }, tooltip: { pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>' }, accessibility: { point: { valueSuffix: '%' } }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true }, showInLegend: true } }, series: [{ name: 'counts', colorByPoint: true, data: [ {% for item in dataset %} { name: {{ item.category }}, y: {{ item.issues }} }, {% endfor %} ] }] }); </script> Kindly let me know what I should change in order to populate the pie chart. Thanks in Advance. -
Heroku yields Application Error when I navigate to django admin site
I get an Application Error from Heroku every time I put in the admin credentials and try to navigate to the admin site on a successfully deployed app. The Django admin site works locally and even worked on Heroku a few times. I am guessing that somehow links are broken or the admin urls aren't set up properly. Everything on the website otherwise works as intended (including login options and things that have restricted access to logged-in users). The app called inv_check and the website is the canonical mysite. The only error I can find on Heroku is: at=error code=H13 desc="Connection closed without response" method=GET path="/admin/"... status=503 Urls for mysite are: urlpatterns = [ path(r'inv_check/', include('inv_check.urls')), path(r'admin/', admin.site.urls), path(r'', include('inv_check.urls')), ] Urls for inv_check are: urlpatterns = [ path('', include('django.contrib.auth.urls')), #accounts/ path(r'', views.index, name='index'), ... ] and I have a menu option to navigate to the admin site: <a href="{% url 'admin:index' %}">Admin site</a> I realize that this may seem like beating the dead horse but I assure you that the superuser does exist and that my procfile is web: gunicorn mysite.wsgi --log-file -. Moreover, local and production sites use the same postgres database hosted on heroku so any local … -
Custom Api function not working during Postman testing
Working on API's so I created a custom function to create and delete a ratings, when running tests on postman to check it's functionality does not seem to work ERROR MESSAGE: User matching query does not exist could this be an error on my code or I am not using postman properly? Below is the code of the function @action(detail=True, methods=['POST']) def rate_movie(self, request, pk=None): if 'stars' in request.data: movie = Movie.objects.get(id=pk) user = User.objects.get(id=1) stars = request.data['stars'] try: rating = Rating.objects.get(user=user.id, movie=movie.id) rating.stars = stars rating.save() serializer = RatingSerializer response = {'message': 'Rating Updated', 'results': serializer.data} return Response(response, status=HTTP_200_OK) except: rating = Rating.objects.create(user=user, movie=movie, stars=stars) serializer = RatingSerializer response = {'message': 'Rating Created', 'results': serializer.data} return Response(response, status=HTTP_200_OK) else: response = {'message':'Stars not selected for rating'} return Response(response, status=HTTP_400_bad_request) Here is also a picture of sample request that I was trying when I wanted to test my function and also the error at which I am getting. -
uwsgi error with ModuleNotFoundError 'xxx.context_processors' use customized context_processors
enter code hereI put my project on server and use uwsgi attempt to start. like.. uwsgi --http :8000 --module myDjangoProject.wsgi it can run, but when i come to my site,append an error.... Internal Server Error: / Traceback (most recent call last): File "/var/www/myDjangoProject/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/var/www/myDjangoProject/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/var/www/myDjangoProject/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "./apps/news/views.py", line 27, in index File "/var/www/myDjangoProject/lib/python3.6/site-packages/django/shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "/var/www/myDjangoProject/lib/python3.6/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/var/www/myDjangoProject/lib/python3.6/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/var/www/myDjangoProject/lib/python3.6/site-packages/django/template/base.py", line 169, in render with context.bind_template(self): File "/usr/lib/python3.6/contextlib.py", line 81, in __enter__ return next(self.gen) File "/var/www/myDjangoProject/lib/python3.6/site-packages/debug_toolbar/panels/templates/panel.py", line 41, in _request_context_bind_template processors = template.engine.template_context_processors + self._processors File "/var/www/myDjangoProject/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/var/www/myDjangoProject/lib/python3.6/site-packages/django/template/engine.py", line 85, in template_context_processors return tuple(import_string(path) for path in context_processors) File "/var/www/myDjangoProject/lib/python3.6/site-packages/django/template/engine.py", line 85, in <genexpr> return tuple(import_string(path) for path in context_processors) File "/var/www/myDjangoProject/lib/python3.6/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in … -
Could i messed up my setting.py or my code itself?
it was working until I made a base.html for the header and the footer. I reversed everything I did to the entire project and rerun the server but it still shows this error. Page not found (404) Request Method: GET Request URL: http://localhost:8000/ Using the URLconf defined in DIALYSIS.urls, Django tried these URL patterns, in this order: admin/ Home.html [name='Home'] contact.html [name='contact'] The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
Proper way to seed data in production django
I have a set of tables that are basically just some definition tables for example: Schedule_table -------- 1|Daily 2|Weekly 3|Monthly Run_type_table -------- 1|Concurrent 2|Singular 3|Multi-prong These are static tables, that should never be edited. I was looking for an approach on how I can ensure these tables are "perfect". Basically when running some command, it cleans up the table to match the seed file exactly. If I remove data from the seed file, it deletes it, if I add a definition, it adds to the database on rerun, etc.. I was looking at this - https://docs.djangoproject.com/en/3.0/howto/initial-data/ but this seems to be an approach for test data. I am looking for something that I can use in production. -
many-to-many relationship of wagtail page model to itself?
So i got a PlantDetailPage model with "companion" field among others (yes plants can be companions), in which I should be able to select other PlantDetailPages. I got the thing to show up, create new plants in inline (yes, a menu in the menu in the menu...), but there's few issues: 1) It just won't select them (no action on clicking "select plantdetailpage") 2) "companions" menu button is now shown on the left (like a snippet that it became?) - which I'd like to avoid. 3) I don't know how to limit the companion inline selector to only selecting and not creating more PlantDetailPages (so that there's no recursion of windows) ? Here's the model in models.py : class PlantCompanion(ClusterableModel): companion = models.ForeignKey( "vegependium.PlantDetailPage", on_delete=models.SET_NULL, related_name="plants", null=True ) plant = ParentalKey( "vegependium.PlantDetailPage", on_delete=models.SET_NULL, related_name="companions", null=True, ) panels = [InstanceSelectorPanel("companion")] class PlantDetailPage(Page): genus_species = models.CharField(max_length=100, blank=False, null=False) # soo many other fields content_panels = Page.content_panels + [ #soo many other panels FieldPanel("alternative_names") ], heading=_("names") ), MultiFieldPanel(heading=_("Companions"), children=[InlinePanel("companions")]), #even more panels ] def get_context(self, request): context = super().get_context(request) context["plant"] = self # needed? # You always can access the page object via "page" or "self" in the template! return context and in … -
Extract month and year then Count and get Average with Grouping by using Django ORM
I want to extract year and month. Then I want to group by year, month and district then count rows and calculate average price for each group. Actually the SQL statement below does what I want to do. So, how can I do this with Django ORM? SELECT district, month, year, COUNT(ilan_no) , TO_CHAR(AVG(price), '9999999999') as avg_price FROM ( SELECT ilan_no, district, price, EXTRACT (MONTH FROM add_date) as month, EXTRACT (YEAR FROM add_date) as year FROM ilan) as foo GROUP BY district, month, year ORDER BY year, month, district models.py: class Ilan(models.Model): ilan_no = models.IntegerField(unique=True, blank=True, null=True) url = models.CharField(unique=True, max_length=255, blank=True, null=True) add_date= models.DateField() origin = models.CharField(max_length=100, blank=True, null=True) city = models.CharField(max_length=20, blank=True, null=True) district = models.CharField(max_length=30, blank=True, null=True) price = models.IntegerField(blank=True, null=True) serializers.py: class IlanSerializer(serializers.ModelSerializer): class Meta: model = Ilan fields = ['ilan_no', 'add_date', 'district', 'price'] I have tried queryset below but value() method didn't work with Rest-Framework serializers. view.py: class IlcePriceAndSizeDistributionListView(ListAPIView): queryset = Ilan.objects.annotate(year=ExtractYear('add_date')).annotate(month=ExtractMonth('add_date')).values('district', 'year', 'month', 'ilan_no', 'add_date', 'price').annotate( ortalama_m2=Avg('m2_net')).annotate(ortalama=Avg('price')).annotate(count=Count('ilan_no')).order_by('year', 'month') serializer_class = IlanSerializer