Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update user data if if user data already exists in django rest api
I have a cart model and I want in API which if the user the add same items two times in cart the cart will automatically increase the quantity of service. In my case, if I add the same item twice it creates another cart instead of updating the previous one. I search about it lot but I don't get an answer. Here is my code:- views.py class CartViewSet(viewsets.ModelViewSet): serializer_class = CartSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): user = self.request.user if user.is_authenticated: if user is not None: if user.is_active and user.is_superuser or user.is_Customer: return Cart.objects.all() raise PermissionDenied() raise PermissionDenied() raise PermissionDenied() filter_backends = [DjangoFilterBackend] filterset_fields = ['date_created', 'user'] @action(detail=False) def count(self, request): queryset = self.filter_queryset(self.get_queryset()) count = queryset.count() content = {'count': count} return Response(content) serializers.py class CartSerializer(serializers.ModelSerializer): class Meta: model = Cart fields = ['id','url', 'user', 'service', 'defects', 'date_created', 'quantity' , 'price', 'total'] models.py class Cart(models.Model): user = models.ForeignKey('accounts.User', related_name="carts", null=True, on_delete=models.SET_NULL) quantity = models.IntegerField(default=1) service = models.ForeignKey('accounts.SubCategory',null=True, on_delete=models.SET_NULL) defects = models.ForeignKey('Defects',null=True, on_delete=models.SET_NULL) price = models.IntegerField(default=False) date_created = models.DateTimeField(auto_now_add=True) total = models.IntegerField(blank=True, null=True) def __str__(self): return self.user.username -
Modeling a field for a large dictionary
We have a field that should only accept the key of a very large dictionary (over 10k key values), the keys are unique but the associated values are many as the dictionary have synonyms. There are many gotchas with this dictionary, however. The dictionary isn't unique in it's key values, due the key values being able to map to synonyms of the terms, also both key and values should be fuzzy searchable, since the users may know the exact key or only part of the values. Since Django is opinionated in its models, I don't know what field I should use to describe it. For smaller dictionaries we are using the *Choices types with the choices option, but as this dictionary is prohibitively bigger it doesn't seem as a sane solution. We were evaluating making the dictionary part of the model using foreign keys, but according to the documentation it requires that the field it makes reference to is set to unique=true, which makes that solution not workable. Using a intermediary model that abstract this away seems to make things more complicated, with the other requirements described in the last sentence of the first paragraphs. Our current conceptual solution is … -
How to solve Authentication Error for connecting gspread to django?
Error 400: redirect_uri_mismatch The redirect URI in the request, http://localhost:8080/, does not match the ones authorized for the OAuth client. This is the error that pops up after run python get_oauth2_token.py which is an script file to get access to google drive and google sheets. Now in my flow variable in my script file I have mentioned redirect_uri as http://localhost:8000 tried setting it as http://localhost:8080 as well. Then I also added redirect_uri for above to addresses in my console.developers.google.com account but to no avail. How do I solve this error? Do feel free to ask me any info. that might solve my query. -
conflict between FilteredSelectMultiple and DatePickerInput in Django?
I have a problem in a django form. imagine the following code : from django import forms from ..models.testModel import Test from django.contrib.admin.widgets import FilteredSelectMultiple from bootstrap_datepicker_plus import DatePickerInput class TestForm(forms.ModelForm): class Media: css = {'all':('/static/admin/css/widgets.css', '/static/admin/css/overrides.css'),} js = ('/static/admin/jsi18n/',) class Meta: model = Test fields='__all__' widgets = { 'date': DatePickerInput(format='%Y-%m-%d').start_of('event days'), 'selector': FilteredSelectMultiple('Selectors', False), } In the html rendering. When I click on the calendar, it doesn't show up. On the other hand, it is displayed when I delete the "selector" from the dictionary widget in the form, and the following error message is displayed : message error is there a conflict between the two modules DatePickerInput and FilteredSelectMultiple, which means the calendar is not displayed if we use FilteredSelectMultiple -
Querrying the images of an product in django
Can any one help me to get just the images of an product i Have this two models: class Product(models.Model): name=models.CharField(max_length=200,null=True) price=models.DecimalField(max_digits=7,decimal_places=2) description=models.TextField(blank=True,null=True) image=models.ImageField(blank=True,null=True,default="images/default.jpg") size=models.ManyToManyField(Size) digital=models.BooleanField(default=False,null=True,blank=True) categories = models.ForeignKey(Category,on_delete=models.SET_NULL,blank=True, null=True) objects = models.Manager() class Images(models.Model): product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True,blank=True) title=models.CharField(max_length=200,null=True,blank=True) image=models.ImageField(blank=True,null=True) def __str__(self): return str(self.title) if self.title else 'image' and in my views.py i use this query to get the images of just a specific product but i get all the images of all the products query = Images.objects.all().query query.group_by=['product'] img=QuerySet(query=query) -
OperationalError at /admin/auth/user/2/delete/ no such table: main.auth_user__old
I have tried to change user permission in the administration page but it actually shows me this when I save Request Method: POST Request URL: http://localhost:8000/admin/auth/user/2/delete/ Django Version: 2.1.5 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: C:\Anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 298 Python Executable: C:\Anaconda3\python.exe Python Version: 3.7.6 Python Path: ['C:\Users\User\Desktop\blog', 'C:\Anaconda3\python37.zip', 'C:\Anaconda3\DLLs', 'C:\Anaconda3\lib', 'C:\Anaconda3', 'C:\Anaconda3\lib\site-packages', 'C:\Anaconda3\lib\site-packages\win32', 'C:\Anaconda3\lib\site-packages\win32\lib', 'C:\Anaconda3\lib\site-packages\Pythonwin'] Server time: Prş, 13 Ağu 2020 18:49:05 +0300 -
django.urls.exceptions.NoReverseMatch: Reverse for 'todo_board_detail' not found. 'todo_board_detail' is not a valid view function or pattern name
I'm in trouble now. How can I slove it? And why did you have the following problem? I am not sure because I am new to django. urls.py app_name = 'todo_board' urlpatterns=[ url(r'^$', views.Todo_board.as_view(), name='todo_board'), url(r'^insert/$', views.check_post, name='todo_board_insert'), url(r'^(?P<pk>[0-9]+)/detail/$', views.Todo_board_detail.as_view(), name='todo_board_detail'), ] urlpatterns+=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py class Todo_board_detail(generic.DetailView): model = TodoList template_name = 'todo_board/todo_board_detail.html' context_object_name = 'todo_list' todo_board_detail.html {% extends 'todo_main/common/header.html' %} {% load static %} {% block main %} <section id="blog"> <div class="container"> {{ todo_list }} <h2>{{ todo_list.title }}</h2> <p> {{ todo_list.content | linebreaksbr}}</p><br> </div> </section> {% endblock main %} -
Django - Annotations based on single object from queryset in queryset
I am looking for a way to make several annotations based on an object from a queryset in a queryset. So let's say I have ObjectA, ObjectB -which has a foreign key to an ObjectA- and ObjectC -which has a foreign key to an ObjectB-, and in my DB there will always be zero to one ObjectB for a given date for a given ObjectA, so I want to do something like: from django.utils.timezone import now today = now().date() object_a.objects.filter(...) .annotate(todays_object_b=LookupOneObjectFrom(object_b_set, today)) .annotate(x=F("todays_object_b__x")) .annotate(y=F("todays_object_b__y")) .annotate(sum_z=Sum("todays_object_b__object_c__z")) Is there a way to achieve it? The only way so far I've found of doing it is through Sum(..., filter=Q(...)) and prefetch_related(Prefetch()) but I question the efficiency of doing the same filter over and over, OR if prefetching, doing the calculations for every ObjectA within the DjangoObjectType. Any pointers are appreciated. -
Django form doesn't pass is_valid
So basically, I want to make a modelForm with hidden input with an initial value of self.object, that only has a submit button. I initialize its value in get_context_data but it does not pass is_valid method. form.errors return: <ul class="errorlist"><li>listing<ul class="errorlist"><li>Enter a list of values.</li></ul></li></ul> models.py class Watchlist(models.Model): """Items on user's watchlist""" user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="watchlist_items") listing = models.ManyToManyField(Listing, blank=True, related_name="users_wanted") class Meta: verbose_name = 'watchlist' def __str__(self): return f'{self.listing}, {self.user}' forms.py class WatchlistForm(forms.ModelForm): class Meta: model = Watchlist fields = ['user', 'listing'] widgets = {'user': forms.HiddenInput(), 'listing': forms.HiddenInput()} def __str__(self): return f'{self.user.username}, {self.listing.title}' views.py get_context method def get_context_data(self, **kwargs): context = super(ListingDetail, self).get_context_data(**kwargs) context['bid_form'] = CreateBidForm() # this form is having troubles with validation context['watchlist_form'] = WatchlistForm(initial={ 'user': self.request.user, 'listing': self.object }) try: context['bid_amount'] = Bid.objects.filter(listing=self.object.pk)[0].bid_amount except IndexError: context['bid_amount'] = 0 return context Although, if I change listing field on Watchlist model from m2m to FK relation, it working as should. Thank you for your time -
Django ImageField validation Issue
The built in validation for django ImageField is failing to add a random string of 7 characters* when uploading images with the following name; example.PNG example.png Different screenshot software will save images as .png or .PNG and there doesn't seem to be any good reasoning for this, however it is getting past django validation. This went unnoticed and caused problems moving our database to a new server, some images were lost and replaced by the latest version (i.e example.png clients now showed example.PNG) How can I add to the validation so it checks before the filetype, so it is just checking for files named example before introducing the random 7 characters? https://docs.djangoproject.com/en/3.1/howto/custom-file-storage/#django.core.files.storage.get_alternative_name get_alternative_name(file_root, file_ext)¶ -
Create a 'dummy' URL path for frontend pictures rendering
I have application with DjangoRestFramework for backend and Vue.js for frontend. My user can upload pictures and they are stored in an uploaded_media file. Therefore I added + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to my urlpatterns. But since it is a Single Page Application, I added re_path(r"^.*$", IndexTemplateView.as_view(), name="entry-point"), in my urlpatterns for everything to be redirected to my index.html. My issue is since my pictures URL is fetched in this format: "http://127.0.0.1:8000/media/my_pic.jpg", it can't be rendered frontend because it's redirected to my entry-point. So I made a 'dummy' URL path (path('media/', DummyView.as_view())) pointing to a dummy View: class DummyView(TemplateView): pass And it works... just for the first picture. I am doing it right and missing something or I am going to the wrong direction? -
How do I create a random url in Django?
I'm getting page not found(404). So far my Django looks like this: tokens.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type from django.utils.crypto import get_random_string import uuid class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( text_type(user.pk) + text_type(timestamp) + text_type(user.is_active) ) account_activation_token = TokenGenerator() views.py from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout from .forms import SignupForm from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes, force_text from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.template.loader import render_to_string from .tokens import account_activation_token from django.contrib.auth.models import User from django.core.mail import EmailMessage from django.contrib.auth.forms import AuthenticationForm from django.db import IntegrityError from django.contrib.auth.decorators import login_required def new_session(request): if request.method == 'POST': current_site = get_current_site(request) user = request.user url = 'http://'+ current_site.domain +'/session/'+str(urlsafe_base64_encode(force_bytes(user.pk)))+str(account_activation_token.make_token(user)) return(render(request,'home/dashboard.html',{'url':url,'session_message':'Your session has been created!'})) def user_session(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): return(render(request,'home/session.html')) urls.py urlpatterns = [ path('newsession/',views.new_session,name='new_session'), url(r'^session/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',views.user_session, name='user_session'), ] So a quick summary, A user clicks a button on a form to generate a random URL. This form posts to new_session. The URL would pop up on the screen for the user. Next the user clicks … -
Django: Password function issues with views.py
I am currently making a web-application for a small group, and I want to set a password that users need to enter when they sign up. I am using django-allauth in this project. In the signup.html below, I added a input tag so that the users can enter a password that is originally set by an administer. Then in the views.py, there's hash and I tried to write a if function that decides whether users can pass the signup.html. Does it have any security issues? If it doesn't, how can I install the function? signup.html {% extends "account/base.html" %} {% load i18n %} {% block head_title %}{% trans "Signup" %}{% endblock %} {% block content %} <h1>{% trans "Sign Up" %}</h1> <p>{% blocktrans %}Already have an account? Then please <a href="{{ login_url }}">sign in</a>{% endblocktrans %}</p> <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {{ form.as_p }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button type="submit">{% trans "Sign Up" %} &raquo;</button> <!-- Here --> <label>Password<input type="text" name="password-input"></label> </form> {% endblock %} users/views.py class SignupView(allauth_views.SignupView): def passowrd_confirmations(request): password_for_site = hash(request.GET.get('password_for_site')) if password_for_site == ngvmXi6T: else: def get_context_data(self, **kwargs): context … -
Django + Celery + Apache mod_wsgi + Postgres + RabbitMQ Application for multiple clients
I have a Django Application that uses Celery, RabbitMQ, with Apache mod_wsgi. Currently all on one server. Each client has their own URL mount, eg: www.example.com/Client001 www.example.com/Client002 www.example.com/Client003 Each client has their own database and project directory with local_setting.py for their Django settings. I'm using supervisord to manage Celery Worker + Celery Beat for each client. As I get more clients so maintaining gets more time consuming. I've started playing with Docker to try and simplify deployments, and probably scale across multiple hosts. Whilst it's quite easy setting up Docker Compose to run a group of services for one client, I'm trying to figure out the best approach for multiple clients that is easy to manage, e.g. quickly setup a new client mounted under the main URL. I'm thinking that the Postgres database instance should be share to hold each clients database, much as it is now. And to have a shared NGIX instance to handle the HTTP side. For each client use a Kubernetes Pod consisting: Gunicorn to handle Django Celery Beat Celery Worker Light weight HTTP server for static files. So the question is, is this a good way or is there a better way of approaching and … -
is there any example for handling MINC data or MRI scanned data using pyhton
I want to take an input of MRI scanned data and play around. I searched and found some information but isn't enough for me to understand. Can anybody explain it please. -
django-channels redis deploy and configuration on ubuntu
I found in Google some old instructions of django-channel deploy, but in my case none of the articles turned out to be a problem solver. I am trying to deploy django project in DigitalOcean's Ubuntu 18.04.3 (LTS) x64 Can you give me step by step instructions or an auxiliary link to help me to deploy django-channels project? -
how this solve this multivaluedictkeyerror in python 3.4?
@api_view(['GET', ]) @permission_classes([]) @authentication_classes([]) def does_account_exist_view(request): if request.method == 'GET': check_mail = request.GET['email'].lower() print(check_mail) data = {} try: account = Account.objects.get(email=check_mail) data['response'] = check_mail except Account.DoesNotExist: data['response'] = "Account does not exist" return Response(data) This code is running fine in python 3.8.5, but on my server python 3.4.3 why this telling error like this? MultiValueDictKeyError at /api/account/check_if_account_exists 'email' Request Method: GET Request URL: http://127.0.0.1:8000/.../.../check_if_account_exists Django Version: 2.0.13 Python Executable: C:\p3.4_envs\Scripts\python.exe Python Version: 3.4.3 -
Faster way to find latest entry for a given period in Django
I've got a basic event model with the following fields: time_stamp key description I need to return the latest value of description for a given key prior to a given date. Under normal conditions I would use the following query: desc = Event.objects.filter(key=key,time_stamp__lte=date).order_by('-id').values_list('description',flat=True)[0] However in this case the model has 2.5 million records, so it takes about 15 seconds to execute. I managed to get a small improvement in speed by specifying a time_stamp__range, but that limits how far back the latest entry can be which I don't really want. I've done some testing and the order_by('-id') is what's slowing it down. I'm considering splitting the event model into models for types of event keys. This will decrease the number of records per model, but before I go that route, can anybody perhaps recommend a faster way of get the last record of a query-set? -
django regroup with duplicate nametuple
I have code for regroup in django template, like below: {% regroup clients by title.0 as clients_list %} {% for client in clients_list %} {{ client.grouper }} {% for item in client.list %} {% if item.client_link %} <a href="{{ item.client_link }}">{{ item.title }}</a> {% else %} {{ item.title }} {% endif %} {% endfor %} {% endfor %} Sometime I have duplicate nametuple in my results for the same letter, for example - 'd': GroupedResult(grouper='d', list=[<Client: decompany_1>]) GroupedResult(grouper='d', list=[<Client: decompany_2>]) so in result I have two headers with letter 'd' Someone know, how to avoid this? edit views.py class ClientsListView(ListView): model = Client template_name = 'clients/clients_list.html' context_object_name = 'clients' -
Is there a pycharm plugin for showing available Django translations?
I'm working on a big project with lots of translated text. Is there some kind of plugin to show already translated text (maybe with autocomplete) when using {% trans "Text" %} or _("Text")? -
changing from SerializerMethodField() to annotate()
I am new to django and django-rest-framework and I encounter a project where I need to optimize an API endpoint. Found that a SerializerMethodField() is causing a duplicate queries on SQL which I think is a N+1 problem. I am currently reading and trying to explore annotate() but found the logic computation to be complicated and I am stuck on how can I convert this to annotate(). Does anyone have a an idea on how to properly implement this? Please see the below code. Hope anyone can guide me as I already am stuck for several days on this. Thank you very much. serializer.py: class BootcampClassStatisticsSerializer(ModelBaseSerializer): attendance_rating = serializers.SerializerMethodField() def get_attendance_rating(self, instance): attendance_rating = None attendance_count = 0 present_count = 0 bootcampers = instance.bootcamper_set.all() date = self.context.get('date') for bootcamper in bootcampers: attendances = bootcamper.dailyattendance_set.all() if date: attendances = attendances.filter(date=date) present_attendances = attendances.filter(status=constants.PRESENT) if instance.class_type == constants.DAY: attendance_count += len(attendances) * 2 for item in present_attendances: if item.duration == 'wd': present_count += 2 if item.duration == 'hd': present_count += 1 if instance.class_type == constants.NIGHT: attendance_count += len(attendances) present_count += len(present_attendances) if attendance_count: attendance_rating = round(present_count / attendance_count * 100, 2) return attendance_rating class Meta: model = BootcampClass fields = ( 'id', … -
Where should I save gcloud credentials with django
I want to create a simple API, that provides an unique endpoint for a POST request which take a json as a parameter, and upload this json in a bucket to google storage. To do the job, I am using Django framework. I would like to understand the best practices and patterns on how should I structure my api app to do that, and where should I store the gcloud credentials. (By the way, I'm open to suggestions on other (better) ways/technos/frameworks/patterns to do this kind of API) For the moment, I am using google.cloud package and putting all the stuff on the apps.py file ; class ApiConfig(AppConfig): storage_client = storage.Client.from_service_account_json('credentials.json') bucket = storage_client.get_bucket('bucket_name') then in the views.py file, I'm doing the post function definition, using the bucket defined in the apps.py file. class upload_to_bucket(APIView): def post(self, request): if request.method == 'POST': json_file = json.loads(request.body) blob = ApiConfig.bucket.blob(json_file['name']) blob.upload_from_string( data=json.dumps(json_file['json_file_to_upload']), content_type='application/json' ) return Response(json_file['json_file_to_upload']) Thank you for helping me -
How can I display a blog post content and delete it using my modal in django?
I have created a bootstrap modal for my blog home page in django which I would like to use to delete posts and also show the post content prior to deleting. My html to trigger the modal looks like this: <button type="button" data-toggle="modal" data-target="#delete" class="btn btn-danger">Delete</button> Then my modal: <div class="modal fade" id="delete" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times</button> <h3 class="modal-title">Do you really want to delete?</h3> </div> <div class="modal-body"> <p>{{ post.content }}</p> </div> <div class="modal-footer"> <a href="{% url 'post_delete' post.id %}" class="btn btn-danger btn-outline">Yes, Delete</a> <button type="button" data-dismiss="modal" class="btn btn-secondary btn-outline">Cancel</button> </div> </div> </div> </div> My views.py file looks like this: class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Post template_name = 'blog/home.html' context_object_name = 'post' success_url = reverse_lazy('blog_home') And my urls.py file: urlpatterns = [ path('', PostListView.as_view(), name='stream_home'), path('post/new/', PostCreateView.as_view(), name='post_create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post_update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post_delete'), ] Upon attempting to load the page I am shown this error: Reverse for 'post_delete' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/delete/$'] If I remove the delete button the page loads and the modal shows up on click but my {{ post.content }} tag fails to display. Please help... -
All the queries are showing twice with this function in django rest framework
Hello guys I am quite new to django rest framework, I have this function to display the featured products, but the product query results are showing twice when checking with postman. How to resolve this issue? I have posted the response from postman also. I am using a custom paginator. Please find the codes below. class CustomPaginator(PageNumberPagination): page_size = 3 def generate_response(self, query_set, serializer_obj, request): try: page_data = self.paginate_queryset(query_set, request) except NotFoundError: return Response({"response": "No results found for the requested page"}, status=status.HTTP_400_BAD_REQUEST) serialized_page = serializer_obj(page_data, many=True) return self.get_paginated_response(serialized_page.data) class FeaturedProductListView(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get(self, *args, **kwargs): try: user = Account.objects.get(username=self.kwargs['username']) except Account.DoesNotExist: raise NotFoundError store = Store.objects.get(user=user) featured_products = Store.objects.filter(user=user, featured_products__in=store.featured_products.all()) paginator = CustomPaginator() response = paginator.generate_response(featured_products, FeaturedProductListSerializer, self.request) return response This is the response from postman. How to resolve this issue? { "count": 2, "next": null, "previous": null, "results": [ { "featured_products": [ { "id": 1, "user": "adminuser", "title": "T shirt cotton", "image": "/media/store/p_thumbnail/om-black-t-shirt.jpg", "brand": "XYZ company", }, { "id": 4, "user": "adminuser", "title": "Lenovo Windows 10 Laptop", "image": "/media/store/p_thumbnail/aceraspire1-100815704-large.3x2.jpg", "brand": "Lenovo", } ] }, { "featured_products": [ { "id": 1, "user": "adminuser", "title": "T shirt cotton", "image": "/media/store/p_thumbnail/om-black-t-shirt.jpg", "brand": "XYZ company", }, { "id": … -
annotate result not included in Json response
I want to count votes as per Model, and its working fine when i test this query in Django shell but when passing as a json i cannot see the column total_votes when i get Json Response. class Model(models.Model): title = models.CharField(max_length=255, null=False, blank=False) description = models.TextField(null=False, blank=False) class ModelVote(models.Model): model = models.ForeignKey(Model, on_delete=models.CASCADE) vote = models.BooleanField() created_at = models.DateTimeField(auto_now_add=True) from django.core.serializers import serialize class ModelList(View): def get(self, *args, **kwargs): models = Model.objects.annotate(total_votes=Count('modelvote')) return HttpResponse(serialize("json", models), content_type='application/json')