Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use timenow to fetch objects with two dates even if one of the dates is in the past in Django?
I have a trips model that has in_flights and out_flights associated to a Client. I wanted to show which Clients have trips after now so I did the following: ls= Clients.objects.get(nif=nif ClientsDash = (Clients.objects.filter(trip__in_flight__date__gt=timezone.now()).filter(trip__out_flight__date__gt=timezone.now()).distinct()) The problem is, if one Client has one of the flights in the past, or only one of the flights, it won't display the trip. -
Item not checkout using stripe
I am trying to submit a stripe payment using python/django/jquery but with no success. I am not sure where is the problem since I am using the same checkout function from the course I am doing. Therefore, I have print(order_form.is_valid(), payment_form.is_valid()) giving me the outcome of True, False in which payment_form is not valid. follow the code checkout/views.py from django.shortcuts import render, get_object_or_404, reverse, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import MakePaymentForm, OrderForm from .models import OrderLineItem from django.conf import settings from django.utils import timezone from tour_store.models import Destinations import stripe # Create your views here. stripe.api_key = settings.STRIPE_SECRET @login_required() def checkout(request): if request.method == "POST": # call the two forms that will be used order_form = OrderForm(request.POST) payment_form = MakePaymentForm(request.POST) # Then will check if both forms are valid if yes, save print(order_form.is_valid(), payment_form.is_valid()) if order_form.is_valid() and payment_form.is_valid(): order = order_form.save(commit=False) order.date = timezone.now() order.save() cart = request.session.get('cart', {}) total = 0 for id, quantity in cart.items(): destination = get_object_or_404(Destinations, pk=id) total += quantity * destination.price order_line_item = OrderLineItem( order=order, destination=destination, quantity=quantity ) order_line_item.save() try: customer = stripe.Charge.create( amount=int(total * 100), currency="EUR", description=request.user.email, card=payment_form.cleaned_data['stripe_id'], ) except stripe.error.CardError: messages.error(request, "Your card was declined!") if customer.paid: … -
Can no longer drop database and reapply migrations in Django?
Throughout writting my app many times I have had to delete my database and re run my migrations. This has always worked by simply deleteing the database file then just running manage.py migrate . However now when I try to do this, I get an error saying django.db.utils.OperationalError: no such table: Planner_course where Planner is my app name and Course is one of my class schemas. What I am doing essentially follows this answer.I am unsure why less than a week ago I was able to reset my database using this method and now I cannot. Does anybody have any ideas? I get error wether I run makemigrations migrate or even runserver, where as everyother time it would simply remake the db and apply the migrations when I reran the migrations with no db. Here is the full error code: "C:\Program Files\JetBrains\PyCharm 2019.3.3\bin\runnerw64.exe" C:\Users\cabra\AppData\Local\Programs\Python\Python38-32\python.exe "C:\Program Files\JetBrains\PyCharm 2019.3.3\plugins\python\helpers\pycharm\django_manage.py" migrate C:/Users/cabra/OneDrive/Desktop/CoursePlanner Tracking file by folder pattern: migrations Traceback (most recent call last): File "C:\Users\cabra\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Users\cabra\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: Planner_course The above exception was the direct cause of the following exception: Traceback (most recent call last): … -
docker-compose up hangs performing system checks
I entered "docker-compose up". It executes but hangs after this line of output: app_1 | Applying sessions.0001_initial... OK I've tried pruning my containers and rerunning but always get stuck here. Here is the entire console output: recipe-app-api on master [⇡!?] on 🐳 v19.03.5 () via 🐍 3.8.1 took 7s ➜ docker-compose up recipe-app-api_db_1 is up-to-date Creating recipe-app-api_app_1 ... done Attaching to recipe-app-api_db_1, recipe-app-api_app_1 db_1 | The files belonging to this database system will be owned by user "postgres". db_1 | This user must also own the server process. db_1 | db_1 | The database cluster will be initialized with locale "en_US.utf8". db_1 | The default database encoding has accordingly been set to "UTF8". db_1 | The default text search configuration will be set to "english". db_1 | db_1 | Data page checksums are disabled. db_1 | db_1 | fixing permissions on existing directory /var/lib/postgresql/data ... ok db_1 | creating subdirectories ... ok db_1 | selecting default max_connections ... 100 db_1 | selecting default shared_buffers ... 128MB db_1 | selecting default timezone ... UTC db_1 | selecting dynamic shared memory implementation ... posix db_1 | creating configuration files ... ok db_1 | running bootstrap script ... ok db_1 | sh: … -
Construct QueryDict from string representation
I have a QueryDict in string form: "<QueryDict: {'order_by': ['-time_updated'], 'page_size': ['500']}>" I wish to construct a QueryDict object from this string. Does QueryDict have a built in way to accomplish this? (the docs don't seem to point towards that) If not, what would be the best way to create it manually? -
Using both Django and Express
I have this problem. I'm working on this app with Express and I have an API made with Django. Now, what I want is to get the API response on my NodeJs app. For example router.get('/v1/users', (req, res) => { res.send('Django Data') }) I'm using cors and it seems everything is alright but I have no idea how can I get the data. // ./app.js const express = require('express') const cors = require('cors') ... const apiRouter = require('./routes/api') const app = express() app.use(cors({ origin: 'http://127.0.0.1:8000/' })) ... app.use(express.json()) ... app.use('/api', apiRouter) ... module.exports = app Does someone have an idea of what can I do to get the data from my Django API? -
save some model field from form django
I'm new in django. i have a question ... i have a model with some fields and i want to get just some of these fields from a form and store in db ... is it possible?! models.py class motors(models.Model): agent = models.ForeignKey(agent_model.agents, on_delete=models.CASCADE) users = models.ManyToManyField(user_model.users, through='user_motors') price = models.FloatField(default=0) serial = models.TextField() produce_date = models.DateField(default=now) name = models.CharField(max_length=200, blank=False, default='') pic = models.ImageField(upload_to='motor images/', null=True) forms.py class MotorSignUpForm(forms.Form): name = forms.CharField() serial = forms.CharField() price = forms.FloatField() pic = forms.ImageField() class Meta: model = models.motors fields = ('name', 'serial', 'price', 'pic', ) views.py def motor_register(request): if request.method == 'POST': form = forms.MotorSignUpForm(request.POST) if form.is_valid(): motor = form.save(commit=False) motor.refresh_from_db() motor.motors.name = form.cleaned_data.get('name') motor.motors.serial = form.cleaned_data.get('serial') motor.motors.price = form.cleaned_data.get('price') motor.motors.pic = form.cleaned_data.get('pic') motor.save() return redirect('user/index') else: form = forms.MotorSignUpForm() return render(request, 'motor/signup.html', {'form': form}) -
Django self.save() not updating the status of the model
I have a very simple model and view py file for cats (trying to test out/learn basic features of django. However the cat's happiness status never really updated. class Cats(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE) name = models.CharField(max_length = 200) description = models.TextField() happiness = 6 def pet(self): self.happiness = self.happiness+1 self.save() from django.shortcuts import render, get_object_or_404 from .models import Cats def cat_detail(request, pk): cat = get_object_or_404(Cats, pk=pk) return render(request, 'cats/cat_detail.html', {'cat': cat}) def cat_interact(request, pk, action): cat = get_object_or_404(Cats, pk=pk) pet = False if(action == 1): cat.pet() pet = True return render(request, 'cats/cat_interact.html', {'cat': cat, 'pet': pet}) action will always be 1 (that's the only current action possible). Inside the html file of both "detail" and "interact" I print out the happiness status of the cat. When I go to the interact page, the cat's happiness status is printed as 7 (since default/start happiness is 6). I expect this value (7) to be saved to the database and when I go to the detail page again it also prints 7. However, even after running the function cat.play() on the detail page it still prints 6, which is the default. Is the 7 never saved to the data base? … -
Chained drop down fileds
lets say that i have this 3 tables class Dhmos(models.Model): name = models.CharField(max_length=100,verbose_name='Πελάτης', blank=False) address = models.CharField(max_length=100,verbose_name='Διεύθυνση', blank=True,default='-') city = models.CharField(max_length=100,verbose_name='Πόλη', blank=True,default='-') phone = models.CharField(max_length=100, verbose_name='Τηλέφωνο', blank=False) fax = models.CharField(max_length=50, verbose_name='Fax', blank=True) teamviewer = models.CharField(max_length=60, verbose_name='TeamViewer', blank=True) email = models.EmailField(blank=True) website = models.URLField(max_length=250, blank=True, null=True) info = models.TextField(max_length=1000, verbose_name='Πληροφορίες', blank=True) is_visible = models.BooleanField(default=False,verbose_name='Κατάσταση') class Meta: verbose_name = 'Πελάτες' verbose_name_plural = 'Πελάτες' ordering = ['id'] def __str__(self): return self.name class Employee(models.Model): dhmos = models.ForeignKey('Dhmos', on_delete=models.CASCADE, verbose_name='Πελάτης', null=True) firstname = models.CharField(max_length=150, verbose_name='Όνομα', null=True) lastname = models.CharField(max_length=150, verbose_name='Επώνυμο', null=True) tmhma = models.CharField(max_length=100, choices= tmhma_choice, verbose_name='Υπηρεσία', blank=True) phone = models.CharField(max_length=100, verbose_name='Τηλέφωνο', blank=False) cellphone = models.CharField(max_length=30, verbose_name='Κινητό', blank=True) email = models.EmailField(blank=True) info = models.TextField(max_length=1000, verbose_name='Πληροφορίες', blank=True) is_visible = models.BooleanField(default=False,verbose_name='Κατάσταση') class Ergasies(models.Model): dhmos = models.ForeignKey('Dhmos', on_delete=models.CASCADE, verbose_name='Πελάτης', default='-') importdate = models.DateField(default=datetime.date.today,verbose_name='Ημ. Κατ.') app = models.CharField(max_length=100, choices=app_choice,verbose_name='Εφαρμογή', blank=True) jobtype = models.CharField(max_length=100, choices=job_choice, verbose_name='Τύπος Εργασίας', default='TeamViewer') info = models.TextField(max_length=1000, verbose_name='Περιγραφή') text = models.TextField(max_length=1000, verbose_name='Σημειώσεις', blank=True) employee = models.ForeignKey('auth.User', max_length=100, verbose_name='Υπάλληλος', on_delete=models.CASCADE,default='-')#delete kai time = models.CharField(max_length=20,verbose_name='Διάρκεια', default=0) name = models.CharField(max_length=100, verbose_name='Υπάλληλος Επικοιν.', null=True,help_text='Επώνυμο-Όνομα', blank=True) ticketid = models.CharField(max_length=50,verbose_name='Αίτημα OTS', blank=True) When i add a record to Ergasies table i want when i choose Dhmos to filter the Employees and display only employees related to Dhmos. How can i do that, … -
dash_bootstrap_components.min.js not found when running Dash inside Django
I am getting dash_bootstrap_components.min.js not found when i try to integrate Dash with Django. Installed dash_bootstrap_components for Dash css Dash Python: external_stylesheets = ['https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css'] app = DjangoDash('SIPPage',external_stylesheets=external_stylesheets) -
Django model.delete() reseed primary key
Busy developing my Django app and as it goes I have test data that I would like to delete from some of my tables. How can I delete the entries and "reset" the primary keys so that the next time an element is inserted, it has id=1? When I run .delete() I am able to delete the row, but the primary key is not reset. According to a bit of research this is standard with databases and I need to truncate the table. Some suggestions are to Truncate the table with raw SQL code: import sqlite3 conn = sqlite3.connect('db.sqlite3') cur = conn.cursor() cur.execute("TRUNCATE TABLE 'table'") which does not seem to work and just gives the following error: OperationalError: near "Truncate": syntax error Other suggestions are to comment out the model and redo migrate. This is not an option either as there are multiple dependent foreign keys across the tables. Is there no way to reset the primary key of a table? -
Restrict options to a ChoiceField Django
thanks for your time: i'd like to know if there is a way to restrict an option on a choicefield if other field starts with a letter 'A': basically i want to don't let the user set the choice (2, 'GATO') on Animal.tipo if his name starts with letter 'a' on People.nome models.py: from django.db import models from django.core.validators import RegexValidator class People(models.Model): nome = models.CharField(max_length=200) birthday_date = models.DateTimeField() cpf = models.CharField(max_length=11, validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return '%s' % (self.nome) class Animal(models.Model): field_choices = [ (1, 'CACHORRO'), (2, 'GATO'), (3, 'OUTRO'), ] pessoa = models.ForeignKey(People, on_delete=models.CASCADE) name = models.CharField(max_length=100) tipo = models.IntegerField(choices=field_choices) custo = models.DecimalField(max_digits=7, decimal_places=2) def __str__(self): return '%s %s' % (self.pessoa, self.name) def cant_have_cat(self): self.maiusculo = self.pessoa.upper if self.maiusculo[0] == 'A': self.tipo != 2 -
PostgreSQL psycopg2 error: there is no unique constraint / InvalidForeignKey
I have the following models: class Contact(models.Model): email = models.EmailField() class EventList(models.Model): event_contacts = models.ManyToManyField(Contact, through=EventMembership) class EventMembership(models.Model): event_list = models.ForeignKey(EventList, null=True, on_delete=models.PROTECT) event_contact = models.ForeignKey(Contact, null=True, blank=False, on_delete=models.PROTECT) However, when applying migrations for EventMembership on a completely clean database I get the following error: psycopg2.errors.InvalidForeignKey: there is no unique constraint matching given keys for referenced table "contacts_contact" class Migration(migrations.Migration): initial = True dependencies = [ ('lists', '0001_initial'), ('contacts', '0002_auto_20200308_2253'), ] operations = [ migrations.CreateModel( name='EventMembership', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('event_contact', apps.utils.django_multitenant.fields.TenantForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='contacts.Contact')), ('event_list', apps.utils.django_multitenant.fields.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='lists.EventList')) ] ] Table contacts_contact clearly has a unique constraint in id as the primary key. What could be causing this error? / How do I debug this? -
How to create a subscriber with PubSub on Google Cloud App Engine that listens to a message via Publisher from a Google Cloud App Engine Flex?
I have a Django Application running on Google App Engine. There is another time consuming application running in Google App Engine Flex that is triggered from the Google App Engine Application. When the Google App Engine Flex Application finished its execution, I want it to trigger a message and send it to Google App Engine Django Application, so Django can update the database item accordingly. How can I use Google Cloud PubSub to achieve this? -
Loops through other loops
Loops through other loops I am trying to insert data from views.py context. How can I avoid in this case looping through other loops. How can I fix it?I am fetching data from wiki by using beautifulsoup. Uploading Image. template.html {%extends 'profilecontent/base.html' %} {%block content%} <div class="container-home"> <div class="home-wrapper home-wrapper-first"> <p class='home-matches'>Przyszłe mecze <span class='home-week'>W3 D2</span></p> <div class="match-wrapper"> <table> {%for second_team in second_team_names%} {%for first_team in first_team_names %} {%for hour_game in hours_games%} <tr><td>{{first_team}}</td><td>{{hour_game}}</td><td>{{second_team}}</td></tr> {%endfor%} {%endfor%} {%endfor%} </table> </div> </div> <div class="home-wrapper home-wrapper-second"> </div> </div> {%endblock%} views.py from bs4 import BeautifulSoup import requests def home(request): source = requests.get('https://lol.gamepedia.com/Ultraliga/Season_3').text soup = BeautifulSoup(source, 'lxml') first_team_names = [] second_team_names = [] td1s = None td2s = None hours_games = ['17:30', '18:30', '19:30', '20:30'] tables = soup.find_all('table', class_='wikitable matchlist') for table in tables: td1s = table.find_all('td', class_='matchlist-team1') td2s = table.find_all('td', class_='matchlist-team2') for td in td1s: span = td.find('span') first_team_names.append(span.text) for td in td2s: span = td.find('span') second_team_names.append(span.text) context = { 'first_team_names':first_team_names, 'second_team_names':second_team_names, 'hours_games':hours_games, } return render(request, 'profilecontent/home.html', context) -
How to connect a database is MySQL Workbench to my website deployed with IIS
I deployed my django project through IIS and have my database stored in mySQL workbench. Can anyone tell me how to connect my website to the MySQL workbench database? Everything I'm finding is very old, 2008/2009, and the instructions are not supported anymore. -
How to show only one object if there's multiple equal objects in Django?
I am sorry for the title but this is the best way I can explain it. I have a trips model that has in_flights and out_flights associated to a Client. I wanted to show which Clients have trips after now so I did the following: ClientsArriving = Client.objects.filter(trip__in_flight__date__gt=timezone.now()) ClientsLeaving = Client.objects.filter(trip__out_flight__date__gt=timezone.now()) ClientsDash = ClientsLeaving | ClientsArriving The problem is, if one Client has an in_flight and an out_flight in the same trip, it will display twice. How can I show the trip only one time? -
Django unable to access admin login page after creating superuser
i am a new python Django learner for the first time i have a problem with access and login admin after creating superuser account python version : 3.7.0 Django version : 3.0.4 below is models.py and i migrated with it. checked my db with sqlite3 which has no problem class Fcuser(models.Model): username = models.CharField(max_length=64, verbose_name='username') password = models.CharField(max_length=64, verbose_name='passward') registed_dttm = models.DateTimeField(auto_now_add= True, verbose_name='regstedtime') this is the urls.py never changed anything from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ] after that, i created a superuser which is successfully done. i started the server with "python manage.py runserver" and access to 127.0.0.1:8000 it is possible to access to access 127.0.0.1:8000 but the problem is... when i try to access to 127.0.0.1:8000/admin there are 3 cases showed up cannot access to the admin page without any error msg. it seems it is automatically shutdown the server. can access to the admin page sometimes but after trying to login with superuser account, it automatically shutdown the server without any error msg again trying to access again with other browser, able to access admin page first but cannot login with the superuser account again, also shows no error … -
How to validate multiple fields in model clean method in Django
In my Django model I am using clean() method to validate two sets of fields' values. I am housing both the conditions in the same clean() method. However I find that the first condition is checked by the system and the second one is ignored. Here is my model and the fields: class Rates(models.Model): master_doc = models.ForeignKey(Origin, ... exit_rate = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True, default=0.00) from_date = models.DateField(null=True, verbose_name='From date') to_date = models.DateField(null=True, verbose_name='To date') def clean(self): if self.exit_rate <= 0: raise ValidationError({'exit_rate': _('The exit rate must more than 0.')}) if self.from_date is not None: if (self.to_date == self.from_date): raise ValidationError({'to_date': _('From Date and end date may not be same.')}) In this instant case, validation error is raised only for the first i.e. field exit_rate. If I reverse the order of the check, validation error is raised for the date fields alone, and not the rate field. I tried this solution and used error_dict but getting error 'ValidationError' object has no attribute 'error_list' How do I ensure that validation error is raised in case either of the conditions are not met? -
Indexing does not work when using postgres with Django
So, the issue is pretty simple but I couldn't find any info related to it >>> Match.objects.all()[0].team_set.all() <QuerySet [<Team: EG>, <Team: Liquid>]> >>> Match.objects.all()[0].team_set.all()[1:2] <QuerySet [<Team: Liquid>]> >>> Match.objects.all()[0].team_set.all()[0:1] <QuerySet [<Team: Liquid>]> >>> Match.objects.all()[0].team_set.all()[0] <Team: Liquid> >>> Match.objects.all()[0].team_set.all()[1] <Team: Liquid> Basically it refuses to give me ForeignKey object by its index. Any ideas? -
In command line, what does "python file.py shell" do?
I have run into a Django tutorial where the instructor is running python manage.py shell. This yields: (env) MBP:Project user$ python3 manage.py shell Python 3.7.6 (default, Jan 8 2020, 13:42:34) [Clang 4.0.1 (tags/RELEASE_401/final)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) Couple questions: What does shell do in python manage.py shell? What does (InteractiveConsole) in the above mean ? I don't see this when I run python without the shell. I have googled InteractiveConsole to no avail. What is "being done" to manage.py here? Is it being "run" or "served"? -
Return extra Fields along with model fields in JSON - Django
I am using a Modelserializer to serialize data. In one of the cases, I have to send some extra fields other than model fields to the UI. How can I do that? Below is my code - My Model - class Group(models.Model): groupID = models.AutoField(primary_key=True, db_index=True) groupName = models.CharField(verbose_name="Name", max_length=30) sectionID = models.ForeignKey(Section, on_delete=models.PROTECT, db_column='sectionID') My Serializer - class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ['groupID', 'groupName', 'sectionID'] My View - @api_view(['GET']) @permission_classes((permissions.IsAuthenticated,)) def getGroupInfo(request): groups = models.Group.objects.all() for group in groups: group.logical_fied = True if <Custom condition> serializer = GroupSerializer(groups, many = True) return Response(serializer.data) Expected response on UI [{ "groupID":1, "groupName":"A", "sectionID":1, "logical_field":True }] Response I am getting [{ "groupID":1, "groupName":"A", "sectionID":1 }] In my serializer.data, I don't get logical_field on the UI as it is not defined in GroupSerializer. Is there any way to achieve this? -
Git merge: conflict I don't know how to resolve
I have a Django project on Git I am not very confortable with Git I have juste finalized, commit and push my feature/22 branch I have commit (after git add .) and push my master So my two branchs are up to date Now, I would like to merge my master with my feature/22 locally but I have an conflict Even after commit, I have 2 files in "Unmerge paths" : Unmerged paths: (use "git add <file>..." to mark resolution) both modified: unblind/migrations/__pycache__/0002_auto_20200124_0904.cpython-37.pyc both modified: unblind/migrations/__pycache__/0003_auto_20200124_1007.cpython-37.pyc What if I use the recommanded command git add? Why these 2 files were not contained in the previous git add . command? -
Django choice field filter the choices
Eu tenho esse meu campo choicefield no meu models onde tem três opções ("Administrador", "Professor", "Bolsista") Porém o que eu quero mostrar na hora de criar um usuario é ("Professor","Bolsista") sem tirar a opção administrador models.py class Usuario(AbstractBaseUser): #1 campo da tupla fica no banco de dados #2 campo da tupla eh mostrado para o usuario TIPOS = ( ('ADMINISTRADOR', 'Administrador'), ('PROFESSOR', 'Professor' ), ('BOLSISTA', 'Bolsista' ) ) USERNAME_FIELD = 'email' tipo = models.CharField(_(u'Tipo do usuário'),null=False, blank=False, max_length=15, choices=TIPOS, default='PROFESSOR') views.py class UsuarioRegisterView(CreateView): model = Usuario template_name = 'usuario/usuario_register_form.html' fields = [ 'nome' , 'email' , 'tipo' , 'password' ] def form_valid(self, form): self.object = form.save(commit=False) self.object.is_active = False self.object.tipo = 'PROFESSOR' self.object.save() return super(UsuarioRegisterView, self).form_valid(form) def get_success_url(self): message = EmailMessage('usuario/email/validacao_email.html', {'usuario': self.object}, settings.EMAIL_HOST_USER, to=[self.object.email]) message.send() return reverse('usuario_register_success') usuario_register_form.html {% extends "usuario/usuario_register_base.html" %} {% load bootstrap3 %} {% block actions %} {% endblock %} {% block title %} {% bootstrap_icon 'user' %} Cadastro de usuário {% endblock %} {% block content %} <form class="form" role="form" method="POST"> {% csrf_token %} {{ form.non_field_errors }} {% bootstrap_form form %} {% buttons submit='Gravar' %} <a href="javascript:history.go(-1);" class="btn btn-info" role="button">Voltar</a> {% endbuttons %} </form> {% endblock %} -
Django Aggregation with a Model that has two foreign key fields pointing to same foreign Model?
I have this model: from reviews.models import * from django.db.models import Count class Review(models.Model): user = models.ForeignKey('core.User') status = models.CharField(default='5 star', max_length=100) reviewed_date = models.DateField(default=datetime.date.today, blank=True, null=True) reviewer = models.ForeignKey('core.User', related_name='reviewer', null=True) I can list the top 5 Review.user's with the most Reviews like this: for u in User.objects.annotate(num_reviews=Count('review')).order_by('-num_reviews')[:5]: ... print u.login, u.num_reviews, u.title ... bobby 395 Manager paul 377 Project Manager micheal 283 Program Manager kim 252 Engineer goober 210 Engineer But how can I list the top 5 Review.reviewers?