Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django AWS-S3 cant start new thread
I set up the project based on here. Everything works fine but whenever I want to upload a larger file (more than 50Mb) using Django admin this error occurs: File "/opt/alt/python37/lib64/python3.7/concurrent/futures/thread.py" in submit 172. self._adjust_thread_count() File "/opt/alt/python37/lib64/python3.7/concurrent/futures/thread.py" in _adjust_thread_count 193. t.start() File "/opt/alt/python37/lib64/python3.7/threading.py" in start 852. _start_new_thread(self._bootstrap, ()) Exception Value: can't start new thread The server is working fine and the resources are enough. On the localhost everything is OK and there is no error. -
URL append with previous URL
In one app (name: loginsystem) I have urlpatterns = [ path('logout/', views.UserLogoutView.as_view(), name='logout'), path('profile/', views.ProfileView.as_view(), name='profile'), path('login/', views.UserLoginView.as_view(), name='login'), path('password_change/', views.UserPasswordChangeView.as_view(), name='password_change'), path('password_reset/', views.UserPasswordResetView.as_view(), name='password_reset'), path('password_reset_done/', views.UserPasswordResetDoneView.as_view(), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', views.UserPasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('password-reset-complete/', auth_view.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] In the other app of urls file I was trying to include these urls and wrote this line path('accounts/', include('loginsystem.urls')), but when i'm trying to access login url from html its append with previous url like this http://127.0.0.1:8000/#/accounts/login/ its add # sign before the url my html <a href="#{% url 'login' %}" class="btn btn-warning">Login</a> this html not in loginsystem app this is in other app -
Django cannot patch in json
Hi I have a model with FileField. I can POST request and fill the field of course using multipart. However, I also have some fields which are non-file for ex. BooleanField. I cannot patch non-file fields when I am using format='json', it needs to be 'multipart' too. How do I enable patch for non-file using json? and Why I am having the error below? class Foo(models.Model): is_published = models.BooleanField(default=False) file = models.FileField(...) class FooSerializer(serializers.ModelSerializer): is_published = serializers.BooleanField( required=False) file = serializers.FileField( use_url=True, required=False) def partial_update(self, request, pk=None): data = request.data.copy() serializer = FooSerializer( pk, data=data, partial=True, ) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) response = self.client.patch( '/apps/foo/1/', data={'is_published': True}, format='json') response: {'detail': 'Unsupported media type "application/json; charset=None" in request.'} -
Django form changing required field depending on another field
I have a django form InstellingenForm that has a few input fields. All should be required. But depending on the input of "spelmodus", either "tijd" or "woorden" should turn to required=False. (if "tijd" is selected in "spelmodus", the "woorden" form should change to required=False and vice versa) I tried to do this with a clean() function, but I can't seem to figure out how to exactly do this. from django import forms SPELMODUS = [ ("", ""), ('tijd', 'Tijd'), ('woorden', 'Woorden'), ] TIJD = [ ("", ""), ('een', '1 minuut'), ('twee', '2 minuten'), ('vijf', '5 minuten'), ] WOORDEN = [ ("", ""), ('vijftig', '50 woorden'), ('honderd', '100 woorden'), ('honderdvijftig', '150 woorden'), ] TALEN = [ ("", ""), ('nederlands', 'Nederlands'), ('engels', 'Engels'), ] MOEILIJKHEID = [ ("", ""), ('makkelijk', 'Makkelijk'), ('gemiddeld', 'Gemiddeld'), ('moeilijk', 'Moeilijk'), ] class InstellingenForm(forms.Form): naam = forms.CharField(label="Naam", max_length=10, required=True, widget=forms.TextInput(attrs={'class': 'input-container'})) spelmodus = forms.ChoiceField(label="Spelmodus", choices=SPELMODUS, required=True, widget=forms.Select(attrs={'class': 'input-container', 'id': 'spelmodus', 'onchange': 'hideShow(this.value)', })) tijd = forms.ChoiceField(label="", choices=TIJD, widget=forms.Select(attrs={'class': 'input-container', 'id': 'tijdClass'})) woorden = forms.ChoiceField(label="", choices=WOORDEN, widget=forms.Select(attrs={'class': 'input-container', 'id': 'woordenClass'})) taal = forms.ChoiceField(label="Taal", choices=TALEN, required=True, widget=forms.Select(attrs={'class': 'input-container'})) moeilijkheid = forms.ChoiceField(label="Moeilijkheid", choices=MOEILIJKHEID, required=True, widget=forms.Select(attrs={'class': 'input-container'})) def clean(self): if self.data.get('spelmodus', 'tijd'): self.fields['woorden'].required = False elif self.data.get('spelmodus', 'woorden'): self.fields['tijd'].required = False super(InstellingenForm, … -
How do I know what functions are run in Generic Views?
I am new to Django and scratching my head with the following question how do I know which function is run in specific processes? for example in below view, retrieve function is executed. I flipped the documentation, however, could not find anything named retrieve to overwrite class ProfileRetrieveAPIView(RetrieveAPIView): serializer_class = ProfileSerializer def retrieve(self, request, username, *args, **kwargs): print("hey yo i am running 01") try: profile = Profile.objects.select_related('user').get( user__username=username ) except Profile.DoesNotExist: raise serializer = self.serializer_class(profile) return Response(serializer.data) -
'QuerySet' object has no attribute 'pk' , how I can get the Id of the post from home view?
How I can get the pk of objects in home view, I try to make personal blog with posts and this posts include comments, I tried to get the post pk in order to get the comments that related to this post but I failed Firstly I tried to get th pk by add it in def home_view(request, pk) but this template in home page www.mywebsite.com that's mean as I know, I cann't pass pk to the url so that's failed with me My qustion is how I can get the Id of the post from home view? My home View post = [] for u in users: p = Account.objects.get(username=u) posts = p.post_set.all() post.append(posts) if len(video): video = sorted(chain(*video), reverse=True, key=lambda video: video.created_date) # here I tried to get the pk comma = Post.objects.all() our_post = Post.objects.get(pk=comma.pk) comment = PostCommentIDF.objects.filter(post=our_post) My Post Model class Post(models.Model): author = models.ForeignKey(Account, on_delete=models.CASCADE) article = models.TextField(null=True, blank=True) photo_article = models.ImageField(max_length=255, upload_to=get_poster_filepath) created_date = models.DateTimeField(auto_now_add=True) My Comment Model class PostCommentIDF(MPTTModel): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='pos_com') parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='post_children') author = models.ForeignKey(Account, on_delete=models.CASCADE) content = models.TextField() created_date = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) The Home View Url path('', home_screen_view, name='home'), -
Django: How to group queryset by timestamp
I have these two models class Blog(models.Model): title = models.CharField(unique=True, max_length=255) class Tag(models.Model): blog = models.ForeignKey(Blog) tag = models.CharField(max_length=255) timestamp = models.DateTimeField(db_index=True) class Meta: constraints = [ models.UniqueConstraint( fields=["blog_id", "timestamp"], name="Timestamp per blog must be unique"), ] Let's say the IDs of some of the blog is [1,2,3,4,5] I want to query and group the tags in such a way that the results is grouped by timestamp. an example output will be like [ {'timestamp': '2021-04-13 15:35:26+00:00', [title_of_blog_id_1]: "hello", 'tag': 'Hello', [title_of_blog_id_2]: "new title", 'tag': 'new'} {'timestamp': '2021-04-13 15:55:26+00:00', [title_of_blog_id_1]: "hello next", 'tag': 'next', [title_of_blog_id_2]: "new updated title", 'tag': 'UP'} ] Explanation of the output: I want a situation in which the Tags are grouped by the timestamp and for each timestamp, it fetches all the blog title and corresponding tag for that timestamp. -
How can I bring the django filters for filtering and searching in a APIView instead of ListAPIView?
Given below was a code written in ListAPIview and now I have to change it to APIView. How can I bring the search, filtering and ordering in this? Please let me know in the comments if any more details are needed. Thanks in advance. class DiscussionView(APIView): pagination_class = DiscussionPagination filter_backends = [OrderingFilter, SearchFilter] search_fields = ['title'] ordering_fields = ['id'] def get(self, request, format=None): query = Discussion.objects.all() serializer = DiscussionSerializer(query, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = DiscussionSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
django annotation queryset for Sum of datetime
i have a model below class UserAttemptQuiz(BaseModel): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='quiz_user') quiz = models.ForeignKey(QuizMcqDetail, on_delete=models.CASCADE, related_name='quiz_detail') start_time = models.DateTimeField() end_time = models.DateTimeField() language = models.ForeignKey(QuizLanguage, on_delete=models.SET_NULL, null=True) score_count = models.PositiveIntegerField() now i wants to sort the users with their time taken to attempt a quiz so i wrote a code by using annotaion function day_ranking_obj = UserAttemptQuiz.objects.filter().values('user').annotate(score=Sum("score_count"),time_taken=Sum( 'start_time') - Sum('end_time')).order_by('time_taken') but i am getting an error below: function sum(timestamp with time zone) does not exist\nLINE 1: ...quiz_userattemptquiz\".\"score_count\") AS \"score\", (SUM(\"quiz_...\n ^\nHINT: No function matches the given name and argument types. You might need to add explicit type casts.\n -
Django Unknown column 'table_name.fieldname_id' in 'field list'
I'm in production mode and using Django==3.1.5 and MySQL and trying to find a way to add a field named author to a model named news without the need to delete the whole database and recreate it. This is the news model and the field: from account.models import User class News(models.Model): ... # The user database is a custom user I've defiend author = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL, related_name='auth_news') Finally, every time I restart the gunicorn service, I end up facing this error: I've tried so many ways to fix this error but no luck! Some of them are: ❌ Deleting the migrations folder, login to MYSQL and DELETE FROM django_migrations; ,then makemigrations and migrate the News model ❌ Facing with a deprecated package named South ❌ using python manage.py migrate news --fake ❌ using python manage.py migrate news zero --fake then remigrate ❌ using python manage.py migrate --run-syncdb --fake ❌ Make initial migrations with --fake-initial When I tried these jobs, all of them worked but none of them added the column author to the news_news table strangely! Then I tried to add it manually: Run python manage.py sqlmigrate news 0001 logging in to the SQL database with command mysql … -
Django tables2 add custom column for another model
I don't know if this question had been covered or not yet, I searcher all the related questions but I couldn't find a solution. What I want to do is to create a table using django-tables2 with a model let's say model A, and I want to add a custom column to this table having value from model B which is not related in any case to model A. This is what I did class TableA(tables.Table): class Meta: model = A template_name = "django_tables2/bootstrap.html" fields = ("id","username","data_from_b") Where can I put the B.objects.filter() to append it's data to a custom column. Your help would be appreciated. Thanks. -
How to redirect a form to a panel tab in views?
I created several tabs with bootstrap in my Django project. I have a form in my second tab (pills-approval-tab). What I want is when a user fills the form, it should redirect the page to the same second tab (pills-approval-tab). I have just 2 tabs. How can I do that? views.py if request.method == 'POST' and request.POST.get('form') == 'risk': form = PdfRiskForm(request.POST, request.FILES, instance=pdf) if form.is_valid(): this_pdf = form.save() ... redirect('????') else: form = PdfRiskForm() ocr.html ... <div class="card-body"> <ul class="nav nav-pills nav-primary" id="pills-tab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="pills-ftables-tab" data-toggle="pill" href="#pills-ftables" role="tab" aria-controls="pills-ftables" aria-selected="true">Financial Tables</a> </li> <li class="nav-item"> <a class="nav-link" id="pills-approval-tab" data-toggle="pill" href="#pills-approval" role="tab" aria-controls="pills-approval" aria-selected="false">Approval</a> </li> </ul> <div class="tab-content mt-2 mb-3" id="pills-tabContent"> {% include './financial_tables_tab.html' %} {% include './approval_tab.html' %} </div> approval_tab.html <div class="tab-pane fade" id="pills-approval" role="tabpanel" aria-labelledby="pills-approval-tab"> ... </div> -
POST Request creates multiple objects AJAX/Django Rest Framework
I am trying to enable a user to create a new list for a dashboard. The problem I have is that when the user creates a new list the following behaviour occurs: User creates first list: The new list appears once User creates a second list: the second list appears twice User creates a third list: the third list appears three times ETC. I'm not sure why this behaviour is occurring. Ajax Call: //create new list const createNewList = function(){ $("#newlistmodal").modal('show'); $("#save-list").click(function() { var listName = $("#newListName").val(); $.ajax({ type: 'POST', url: '/api/userlist/', data: { csrfmiddlewaretoken: document.querySelector('input[name="csrfmiddlewaretoken"]').value, 'list_name' : listName }, success: function(data) { console.log(data.instance_id) var listId = data.instance_id; $("#newlistmodal").modal('hide'); $("#userLists").append( `<li class="userlist" id="${listName}" data-name="${listName}" data-pk="${listId}"> ${listName} <i id="dropdown" class="ml-4 dropdown fas fa-ellipsis-h" type="button" data-toggle="dropdown"></i> <div class="dropdown-menu dropdown-menu-left" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" id="${listName}-edit" data-name="${listName}" data-pk="${listId}">Edit List</a> <a class="dropdown-item" id="${listName}-share" data-name="${listName}" data-pk="${listId}">Share</a> <a class="dropdown-item" id="${listName}-delete" data-name="${listName}" data-pk="${listId}">Delete</a> </li> `) } }); }); } Views.py (Using DRF) class UserListViewSet(viewsets.ModelViewSet): serializer_class = UserListSerializer def get_queryset(self): return UserList.objects.filter(user__username=self.request.user) def create(self, request): serializer_class = UserListSerializer if self.request.method == "POST": user = self.request.user.id list_name = request.data.get('list_name') data = {'user': user, 'list_name': list_name} serializer = serializer_class(data=data) if serializer.is_valid(): instance = serializer.save() return Response({'status' : 'ok', 'user' : user, 'instance_id':instance.id}, … -
How to get over this Heroku-Redis error? SSL routines:ssl3_get_record:wrong version number
I am building a Django app using django channels and redis. Running it locally on redis works fine but when pushing it on Heroku with Heroku-Redis v6.0.12 i get the bellow error: Error accepting a client connection: error:1408F10B:SSL routines:ssl3_get_record:wrong version number. My settings.py for the Redis part looks like this : import os ... ALLOWED_HOSTS = ['*',] ... CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": os.environ.get('REDIS_URL'), "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "CONNECTION_POOL_KWARGS": { "ssl_cert_reqs": None }, } } } CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": ['redis://:*****@****.amazonaws.com:27810'], }, }, } What am I doing wrong? -
Can't get model records in migration using RunPython after new field is created
Problem: I've created a new field named "new_field" in my model MyModel, created migration "01" which added this field. After that I want to change model records with respect to some old field "old_field" in new migration "02" So I've created migration "02" which changes my records using RunPython, it might look like this: . from ..models import MyModel def update_model(): for record in MyModel.objects.all(): record.new_field = record.old_field record.save() class Migration(migrations.Migration): dependencies = [('myapp', '01')] operation = [migrations.RunPython(update_model, lambda *args: None)] This migration will run fine, but after that I want to create new field "super_new_field": I'm creating migration "03" which creates new field "super_new_field" Everything will be fine. But if I'll clear database and then run migrations, migration "02" will not work since it's trying to access MyModel which does have field "super_new_field" in Django, but it's still missing in database since migration "03" was not executed yet. This means this code has to be removed (or order of migration and everything else must be changed) in order for migrations to be executed on new enviroments, which is not good Question: Is there a way to update model records inside migrations and avoid this problem? Migrations seems to be … -
Django admin User fields value in a model related list
In my django admin project i have a model like thisone: from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, ) u_name = models.CharField(max_length=200, verbose_name="Nome") u_sname = models.CharField(max_length=200, verbose_name="Cognome") ... so in my admin pge i would in list make visible also some fields related to User model like for example username, email, is_active, i do: list_filter = ('u_prov',) list_display = ('u_sname', 'u_name','user__username',) ... but i get: The value of 'list_display[3]' refers to 'user__username', which is not a callable, an attribute of 'UserAdmin', or an attribute or method on 'agenti.UserProfile'. How can i display fields of User model in my related model django-admin list? So many thanks in advance -
Can't pass parameter from template to Django view
Im passing three parameter from my html template to django view.py. But whenever i click on submit it show me Page not found ,. I'm still new in programming and Django. Does anyone know how can I fix this issue? The expected result is the webpage able to display all the input from the user. The result should display on the same page and not on the other pages. my template <!-- The Modal --> <div id="myModal" class="modal"> <!-- Modal content --> <div class="modal-content"> <div class="modal-header"> <span class="close">&times;</span> <h2>Alert Policies</h2> </div> <div class="modal-body"> <p style="font-size:14px">Please select an event parameter as well as the condition type and value that apply.</p> <!-- parameter drop down --> <form action="send" method="post"> <label for="Parameter"> <b style="font-size:13px" > Event parameter to evaluate </b></label> <select name="Parameter" id="Parameter" style="width:340px; font-family: 'Quicksand', sans-serif;"> <option disabled selected value>select a parameter</option> <option value="Subject">Subject</option> <option value="Text">Text</option> </select> <br><br> <label for="Condition"> <b style="font-size:13px" > Type of condition </b></label> <select name="Condition" id="Condition" style="width:340px; margin-left:69px; font-family: 'Quicksand', sans-serif;"> <option disabled selected value>select a condition</option> <option value="Equals">Equals</option> <option value="Contain">Contain</option> <option value="NotContain">Does not contain</option> </select> <br><br> <label for="valuetomatch"> <b style="font-size:13px" > Value to match</b></label> <input type="text" id="valuetomatch" name="valuetomatch" style="width:333px; margin-left:80px; font-family: 'Quicksand', sans-serif;"> <br> <br> <button class="button"><span>OK</span></button> … -
how to encrypt my website to against political review
I built a website to discuss philosophy. using the server of Aliyun Hong Kong. The frontend is vuejs. the backend is Django + MySQL. I want to encrypt the comments posted by users to prevent censorship(against political review). Q1. What legal problems will there be if users post violent comments on my website? Q2. how to embed encryption code in my website. Should I encrypt and decrypt just in the front-end, and only save the encrypted text on the database side? -
Django admin - handling permissions of many to many fields
Let's say I have 2 models as follows. As there is a many to many relation between the models, django created the required table (clientreport) and the table's permissions can be set using django admin's group permission's tab. (see screenshot) class Report(models.Model): is_visible = models.BooleanField(default=False) clients = models.ManyToManyField(Client) class Client(models.Model): name = models.CharField(max_length=32) On django admin I granted change permissions to a specific user group (e.g. group_a) on Report model. I did NOT grant any permissions on clientreport model. My desired output is, a group_a user can change is_visible field of any Report instance but could not change/delete client X reports (or clientreport). However even if there is no actual table reference between Report and Client models, a group_a user can still edit client-reports from django admin panel. (see screenshot) Is this really intended? If so, how can I get my desired goal? -
Adding extra input fields on user need and saving and fetching the values in django
I m working on a website In DJANGO where in i need to add input fields dynamically on a button click and then clicking the Submit button saves the data in Django Database How to do this and also fetch the saved data for the input fields. Example in a college a person is allowed to take as many subjects he needs. He may take 1 subject or 2 subjects or more. When he fills the form only 1 input field is shown. If he wants to add one more subject he clicks on the "Add" button and one more field is generated after this he clicks the Submit button to save the data. How to save that dynamic data created when button was clicked and then fetch it to show in template -
Django framework
I m trying to get the email of the person who just login. if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') email = request.POST.get('email') -
Django raise IntegrityError exception befor form.save()
I have a model with a unique "code" field and a form for the same model where the "code" field is hidden. I need to set the "code" value in the view after the user has copied the form, but I get an IntegrityError exception. model class Ticket(models.Model): codice = models.CharField(unique=True, max_length = 13, default = '') form class NewTicketForm(forms.ModelForm): codice = forms.CharField(widget = forms.HiddenInput(), required=False) view if request.method == 'POST': form = NewTicketForm(request.POST) form.codice = 'MC-PR' + get_random_string(length=8, allowed_chars='0123456789') if form.is_valid(): while True: try: codice = 'MC-PR' + get_random_string(length=8, allowed_chars='0123456789') form.codice = codice form.save() except: break form.save() return redirect('ticket-homepage') else: form = NewTicketForm() form.codice = 'MC-PR' + get_random_string(length=8, allowed_chars='0123456789') context = { 'form': form } return render(request, 'ticket/new_ticket_form.html', context) I also tried to set form.code before form.is_valid () but the exception is raised anyway. technically there shouldn't be any problems because I generate the value with get_random_string and try-except allows me to do it again as long as the value is not unique. -
difference between django-allauth process='connect/login'
here in the docs there is an optional parameter process which can take either login or connect. using process='login' it works properly and creates new user if there isn't any, while process='connect' does nothing.(I was expecting it to login just if there is a user ..). but i have no idea on, how that works.. I have a loginForm and SignUpForm where both have the social login/signup option, and I don't want it to create account when it's clicked on social icon on LoginForm. how can i perform this. (sorry if messed up things..:) -
Django admin link at user model from another in list
In my django admin i have a model that link to user, i would have n my list create a link for pass to related user id editing page directly from connected models, i do: class a_cards(models.Model): CK_CHOICES = ( ('A', 'Ambassador'), ('M', 'Medico'), ('P', 'Paziente'), ('S', 'Senator'), ) c_num = models.CharField(max_length=200, unique=True, null=True, blank=True, verbose_name="Numero card") c_data = models.DateTimeField(auto_now=True) c_type = models.CharField( max_length=1, choices=CK_CHOICES, verbose_name="Tipo utenza") c_email = models.CharField(max_length=200, unique=True, null=True, blank=True, verbose_name="Notifica Email") c_agente = models.ForeignKey(AgenteProfile, on_delete=models.CASCADE, null=True, blank=True, related_name="ag_id", verbose_name="Agente") c_user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE, verbose_name="Cliente" ) class Meta: verbose_name = 'Cards' verbose_name_plural = 'Cards' def user_link(self): if self.c_user: return '<a href="%s">%s</a>' % (reverse("admin:auth_user_change", args=(self.c_user.id,)) , escape(self.c_user)) user_link.allow_tags = True user_link.short_description = "User" def __str__(self): return self.c_num in admin: class cardAdmin(ImportExportModelAdmin): list_filter = ('c_type',) list_display = ('c_num', 'c_data', 'c_type', 'c_agente', 'user_link',) ... but when i open my admin page i see the correct link but not in libk form: where is the error? why i can't have clickable link? So many thanks in advance -
Django- Group by and Count by unique together
I have following models: class Post(models.Model): title = models.CharField(max_length=30) class PostView(models.Model): post = models.ForeignKey(Post, related_name='views', on_delete=models.CASCADE) user = models.ForeignKey(get_user_model(), related_name='my_views') created = models.DateTimeField(auto_now_add=True) I want to get post views count, grouped by hour of day and unique. for example if a user sees a post at 10 AM 20 times, just one time should be calculated. I get the posts in hours by views (not unique views) as following: from django.db.models.functions import TruncHour from django.db.models import Count qs = PostView.objects.all().annotate( hour=TruncHour('created') ).values( 'hour' ).annotate( c=Count('id') ).values('hour', 'c') above code will calculate all views as total views. I want to get unique views by user_id and hour and post_id together. Is it possible to do that with ORM?