Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I get non exist query condition in Django queryset __in cluase
Assume I have a queryset: Book.objects.filter(pk__in=[1,2,3,4,5]). Is there any easy way(i.e. built-in API) to get which pk does not correspond to any record? -
How can I import my own script into models.py in django
I have created a small script for comparing how similar two images are. This is contained in a file called compare_image.py, which contains just one function, compare. This file is in the app directory. I am trying to import it from the models.py file using the line import compare_image, but attempting this results in the error message ModuleNotFoundError: No module named 'compare_image'. The simplified directory structure looks like this: myproject └── myapp ├── __init__.py ├── admin.py ├── apps.py ├── compare_image.py ├── forms.py ├── models.py ├── tests.py ├── urls.py └── views.py myapp is the only app in the project. Apart from this, the webapp functions fine. I have tried deleting and retouching the __init__.py file to no avail. I can import compare_image fine from a python shell in the myapp directory. The only imports in compare_image.py are to PIL or standard libraries, so I don't think circular imports are the culprit. One solution would be to just put the code in models.py, but I don't want to clutter this file. I thought since this error seems so basic there might be some standard mechanism for user-written scripts in Django, but I can't find any mention of this online. I would be … -
i am trying to create a website using django,pycham and python. while trying to run the code i got this error. can anyone help me with this?
Traceback (most recent call last): File "C:/Users/Akriti/Documents/santulitahar/santulitahar/manage.py", line 10, in execute_from_command_line(sys.argv) File "C:\Users\Akriti\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-1.9-py3.7.egg\django\core\management__init__.py", line 350, in execute_from_command_line utility.execute() File "C:\Users\Akriti\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-1.9-py3.7.egg\django\core\management__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Akriti\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-1.9-py3.7.egg\django\core\management__init__.py", line 176, in fetch_command commands = get_commands() File "C:\Users\Akriti\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-1.9-py3.7.egg\django\core\management__init__.py", line 71, in get_commands for app_config in reversed(list(apps.get_app_configs())): File "C:\Users\Akriti\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-1.9-py3.7.egg\django\apps\registry.py", line 137, in get_app_configs self.check_apps_ready() File "C:\Users\Akriti\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-1.9-py3.7.egg\django\apps\registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Process finished with exit code 1 -
Django: ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
I have a Django application I want to run locally. I am running on win32 with Python 3.7. I enter the following into Command Prompt on Windows: $ python manage.py runserver Django version 2.07, using settings 'web.settings' Starting development server at http://127.0.0.1:8000 Quit the server with CTRL-BREAK. The problem comes when I open to localhost:8000/ in my browser. What happens is I'll get this error in Command Prompt: Traceback (most recent call last): File "C:\Program Files\Python37\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Program Files\Python37\lib\wsgiref\handlers.py", line 180, in finish_response() self.write(data) File "C:\Programs Files\Python37\lib\wsgiref\handlers.py", line 279, in write self.write(data) File "C:\Programs Files\Python37\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "C:\Programs Files\Python37\lib\socketserver.py", line 796, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine I am unsure how to get rid of this error. -
Is it possible to create and connect Django databases from the application?
Is it possible to create and connect Django databases from the application? An example. In a system at the time of user registration, at that time django create a new database generates the migrate and create a new database with the exact settings. -
Subscribe to a redis channel in Django
I have multiple applications written with nodejs or python/django or ... These services are working fine. But need to have pub/sub Async communication with each other. In nodejs there is no problem and easily can pub/sub to any redis channel. Question: My question is how can i continuously subscribe to a redis channel and receive data published with other services? Note: many links suggest to use django-channels. But I guess that's not the way to do it. If so can any one help me and give details on how to do it. Really appreciate it. -
Trying first django project, says /mysite not found
I am following the django tutorial here: https://docs.djangoproject.com/en/2.1/intro/tutorial01/ I have a pc running Win7. I opened a cmd prompt window and cd to c:/Inetpub/wwwroot. I typed: $ pip freeze $ pip install django Django installs. Then I type: $ django-admin startproject mysite $ cd mysite $ python manage.py runserver OK, fine. I go to my browser and look at http://127.0.0.1:8000/ The page says, "It worked!" BUT, in the cmd window, it says: C:\Inetpub\wwwroot\mysite>python manage.py runserver Performing system checks... System check identified no issues (0 silenced). You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. January 31, 2019 - 10:48:20 Django version 1.11.18, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: /mysite [31/Jan/2019 10:49:31] "GET /mysite HTTP/1.1" 404 1947 Not Found: /favicon.ico [31/Jan/2019 10:49:31] "GET /favicon.ico HTTP/1.1" 404 1962 [31/Jan/2019 10:50:10] "GET / HTTP/1.1" 200 1716 [31/Jan/2019 10:50:19] "GET / HTTP/1.1" 200 1716 Now I have no way to type in this window any more AND it says it can't find /mysite. What's going on? What did I do wrong? -
How to send file from Mayan EDMS to external api?
I'm still learning Django and there is still a lot of unknown to me. The problem is that I can't pull the .pdf (or any other format) to be sent by ajax post method to external API. So on the reciving side I only get the string location of the file not the actual file. I have put the following javascript code in the generic_list_items_subtemplate.html {% load i18n %} {% load static %} {% load common_tags %} {% load navigation_tags %} <div class="row"> <div class="col-xs-12"> <h4> {% if page_obj %} {% if page_obj.paginator.num_pages != 1 %} {% blocktrans with page_obj.start_index as start and page_obj.end_index as end and page_obj.paginator.object_list|length as total and page_obj.number as page_number and page_obj.paginator.num_pages as total_pages %}Total ({{ start }} - {{ end }} out of {{ total }}) (Page {{ page_number }} of {{ total_pages }}){% endblocktrans %} {% else %} {% blocktrans with page_obj.paginator.object_list|length as total %}Total: {{ total }}{% endblocktrans %} {% endif %} {% else %} {% blocktrans with object_list|length as total %}Total: {{ total }}{% endblocktrans %} {% endif %} </h4> <hr> <div class="well center-block"> <div class="clearfix"> <div class="pull-right"> <form action="{% url 'common:multi_object_action_view' %}" class="form-multi-object-action" method="get"> {% if object_list %} {% if not … -
Object of type SerializerMetaclass is not JSON serializable DRF
I want to encode data and make a post method using requests and drf, so example is class ProjectViewSet(viewsets.ModelViewSet): logger = logging.getLogger('django') """ API """ queryset = Project.objects.all() serializer_class = ProjectSerializer filter_backends = (filters.OrderingFilter, filters.SearchFilter, DjangoFilterBackend) filterset_class = ProjectFilter ordering_fields = ('name', 'owner', 'project') ordering = ('name') search_fields = ['name'] # create new execution for this project def create(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): encode_data = json.dumps(serializer) response = requests.post( url='{}/process'.format(EXAMPLE_URL), json=encode_data, headers=headers ) logging.debug(f"{self.response}") return Response({'response': response}) The error for this Object of type SerializerMetaclass is not JSON serializable and now I'm confused a bit, I suppose I need to encode data because JSON encoding is done in the Response object, but I'm failing to understand the error, so can someone please explain what is wrong here, thanks. -
Adding all users of a group as choices in a model field
I'm trying to restrict a field in one of my models to a choice of all users that are members of a particular group. Another field hass all registered users a choices. This works fine in the shell: >>> from django.contrib.auth.models import User, Group >>> all_users = User.objects.all() >>> all_users <QuerySet [<User: somedude>, <User: test>, <User: testma>]> >>> tm_users = User.objects.filter(groups__name='Testmanager') >>> tm_users <QuerySet [<User: somedude>, <User: testma>]> But if I put the same code in the model: class TestPlan(models.Model): all_users = User.objects.all() all_user_choices = ((x.username, x.get_full_name()) for x in all_users) tm_users = User.objects.filter(groups__name='Testmanager') tm_user_choices = ((x.username, x.get_full_name()) for x in tm_users) tp_title = models.CharField(max_length=200, verbose_name='Title') tp_manager = models.CharField(max_length=100, blank=True, verbose_name='Test Manager', choices=tm_user_choices) tp_tester = models.CharField(max_length=100, blank=True, verbose_name='Tester', choices=all_user_choices) def __str__(self): return f'{self.tp_title}' I get the following less than helpful (to me) stack trace: O:\somedude\Documents\Python\Django\testcases>manage.py makemigrations Traceback (most recent call last): File "O:\somedude\Documents\Python\Django\testcases\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 381, i n execute_from_command_line utility.execute() File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 357, i n execute django.setup() File "C:\Program Files\Python36\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files\Python36\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Program Files\Python36\lib\site-packages\django\apps\config.py", line 198, in import_mode ls self.models_module = import_module(models_module_name) File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module … -
Django static files not loading for all pages except index page
I am working on a blog website in django, where I can write articles. While developing I am simultaneously hosting it on pythonanywhere.com In dev server everything works perfect, but after deploying, I am facing a strange issue. My static files are loading for home page but are giving error-404 for all remaining pages. While debugging, I found that for home page it searches files in path www.asdf.pythonaywhere.com/static which is correct But for a page say 'www.asdf.pythonaywhere.com/article/1/' it searches for static files in ''www.asdf.pythonaywhere.com/article/1/static' which is incorrect. I searched everywhere on the internet but couldn't find answer. Here are my settings: STATIC_URL = 'static/' STATIC_ROOT = 'static/' This is how I am referring to static files: <link href="{% static "vendor/bootstrap/css/bootstrap.min.css" %}" rel="stylesheet"> -
Is there better way of Django form to url redirect than this?
I am new to Django and working on getting my first application running. The Quiz model encompasses everything and each entry is unique with combination of level,type and year fields. I have searchForm form to let users select and search in index page. I want the user to first select level from available levels then select type from available types which are dependent on the level previously selected, and lastly year from years, also dependent on type. I managed to implement that using Django,Jquery, AJAX and the searchForm below . The problem is, once the user selected the fields and click 'search',this is the resulting url. http://127.0.0.1:8000/?search=&level=01&subject=history&year=2019 I don't have problem matching that in url and redirect to the view I want, like re_path(r'\?search=&level=\d{2}.*type=\w+.*year=\d{4}', Takequiz.as_views(),name='takequiz'). However, it looks ugly from the outset and not sure if it works across browsers as well. How can I accomplish the same task in more professional and userfriendly way? Any suggestions would be appreciated. **in model.py** class Quiz(models.Model): name = models.CharField() level= models.ForeignKey() type= models.ForeignKey() year= models.ForeignKey() class Level(models.Model): level= models.CharField() class Type(models.Model): type= models.CharField() class Year(models.Model): year= models.CharField() **in form.py** class QuizForm(forms.Form): grade = forms.ModelChoiceField( queryset =Grade.objects.all(),to_field_name="grade",required=False) subject = forms.ModelChoiceField(queryset=Subject.objects.none(), required=True ) year … -
Error when deploying django app to heroku
I am trying to push my app to heroku, but I am getting the following error: Counting objects: 1907, done. Delta compression using up to 4 threads. Compressing objects: 100% (1894/1894), done. Writing objects: 100% (1907/1907), 9.86 MiB | 2.10 MiB/s, done. Total 1907 (delta 160), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: /app/tmp/buildpacks/8790c95df255b386056ea169648fd4a33d1cb3fba81f73b536f26374f6af107145f64a5980db7a52177f63bb4152 7f360ebd2e3bef7b8917bda7b51cf284cfdb/bin/steps/python: line 5: warning: command substitution: ignored null byte in input remote: ) is not available for this stack (heroku-18). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to mywebsite. remote: To https://git.heroku.com/mywebsite.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/mywebsite.git' Any ideas? I have the Procfile, requirements.txt, and runtime.txt files -
Django CustomUserModel & Form
After submitting the sign-up form in my Django application, I want to register a User. I want the username to be the email address provided in the form. To do this I create a CostumUser model, to manage this model I also created a CustomUserManager. see models.py I also created a CustomUserCreationForm. see forms.py. My admin.py looks like admin.py. When I try to register a superuser, through command: python manage.py createsuperuser all the required fields are prompted, after completing all the fields, Django returns an error. (see figure below.) Also, when navigating to the signUp form through the browser and sumbitting the form, returns nothing. The form data is not save in the Database, in my views.py I have a line to check if the form is valid -, form.is_valid() this returns True. see views.py I ran: python manage.py makemigrations and python manage.py migrate which returned: and I noticed, after running makemigrations and migrate, the db.sqlite3-journal file does not close. This could be the reason that the database does not update. I think something might be wrong with the model. Some explanation or solution to my peroblem would be appreciated. -
Is it a bad practice for my project folder to also be an application in Django?
Say I have a Django project called myproject. Within this project there will of course be a folder called myproject which will house my settings file and other global configuration files. As my project grew and began to incorporate many different apps, I placed certain functionalities that were common to all of my apps in a utils module in my myproject folder. At this point, I want to write some unit tests for those utils, as well as add some global project commands that I feel it would make sense to house within the myproject folder. To have access to these functionalities, I need to add myproject to my list of installed apps. This works just fine, but I've never seen this done in a Django project. My question is this : Is this a bad practice ? Are there unforeseen risks I'm not seeing here ? A cleaner way of doing things ? Would it be safer to create an app called common and have it house my utils, global commands etc. ? How do you usually organize your modules if they're defining project level functionalities ? -
mac os + apache 2.4.33 + python 3.7.2 + django 2.1.5 + mod_wsgi 4.6.5 (Site can't be reached)
I am facing issue in running the server(Site can't be reached) after python upgrade from 2.x to 3.7.2 Our server config: Mac OS 10.13.6 (High Sierra) Apache 2.4.33 custom installation Python 3.7.2 (Brew install python3) Django 2.1.5 (Installed via pip inside python 3 env) mod_wsgi 4.6.5 (Installed via pip inside python 3 env) I have added the following two lines(mod_wsgi-express module-config) in httpd.conf file replacing the 2.7 references: LoadModule wsgi_module "/../MASP_ENV3/lib/python3.7/site-packages/mod_wsgi/server/mod_wsgi-py37.cpython-37m-darwin.so" WSGIPythonHome "/../MASP_ENV3" Also in httpd-vhosts.conf: WSGIDaemonProcess mysite.com processes=2 threads=15 display-name=%{GROUP} python-home=/Library/WebServer/Documents/MASP_ENV3 python-path=/Library/WebServer/Documents/mysite WSGIProcessGroup mysite.com WSGIScriptAlias / /Library/WebServer/Documents/mysite/wsgi.py After restarting the server, when we hit the URL in the browser the page continues to load for a while(2-5 mins) and later displays "Site can't be reached" It would be great if one can guide me with valuable suggestions. Thanks! -
How to add model form (like inline) to StremField in wagtail?
I think I should use StructBlock, or something like that. But I don't have any idea how to connect block and model. Ofcourse I can use some model signals, override save method in patrent model (which have this stream field), but I guess it is not good solution. Sorry for my bad english -
How to debud django crontab?
I have setup a cron job by using django crontab. As per defined in documentation I defined a test job in cron.py and defined it to run in 1 minute interval in settings.py. #cron.py def test_cron_run(): print("\n\nHello World....!! ",timezone.now()) #settings.py INSTALLED_APPS = [ 'material.theme.cyan', 'material', 'material.admin', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', 'django_crontab', ] CRONJOBS = [ ('*/1 * * * *', 'myapp.cron.test_cron_run','>>'+os.path.join(BASE_DIR,'log/debug7.log')), ] I have added the cron jobs by running python3 manage.py crontab add. Also the job is added as I can see if I run, python3 manage.py crontab show However I cannot see any log file being generated. Is there any way to debug this, the os logs or something? -
Permission denied: '/code/celerybeat.pid'
I can't run Celery beat using Docker. celerybeat_1 | celery.platforms.LockFailed: [Errno 13] Permission denied: '/code/celerybeat.pid' docker service: celerybeat: <<: *django depends_on: - postgres - redis command: /start-celerybeat.sh start-celerybeat.sh #!/bin/sh set -o errexit set -o nounset celery -A my_project.taskapp beat -l info --loglevel=debug --scheduler django_celery_beat.schedulers:DatabaseScheduler How can I fix that? -
Django ORM: Filter on timedelta
I've got a field 'frequency' and i'd like use it in my filter. My model: class Foo(models.Model): name = models.CharField(max_length=50) frequency = models.IntegerField(default='60') last_checked = models.DateTimeField() I'd like get my data some like it, but instead of '10' minutes I can put there 'frequency' field. Foo.objects.filter(last_checked__lt=timezone.now()-timedelta(minutes=10)) How can i do this? Or maybe I shoud go other way? Thanks for helpful tips. -
When passing data from AJAX call it returns None type
I want to pass data from AJAX call.Data wants to be the (form input data+key). When i pass the data it returns the data that i want.But it also returns a None type value. I want to get rid of that None type value. Following shows my form template code. <form action="/seq_input/" method="POST" id="MyForm"><br> <p style="color:black;font-size:14px">These messages haven't reciever.</p> <p style="color:black;font-size:14px">If you want you can add recivers</p> <table id="tb1"> <tr> <th style="display:none;">Key</th> <th>Message</th> <th>Reciver</th> </tr> {% for key,values in NullList.items%} <tr> <td style="display:none;">{{key}}</td> <td>{{values}}</td> <td><input type="text" id="{{key}}" name={{key}} value=""></td> </tr> {% endfor %} </table> <br> <input type="submit" value="SubmitMyInputs" onclick="get_details()"> </form> following shows the Ajax call. var jsonArr = []; function get_details(){ console.log("submit"); console.log(myObject); for(var value in myObject){ var x=document.getElementById(myObject[value]).value; jsonArr.push({ key:myObject[value], reciever:x }); } alert(JSON.stringify(jsonArr)); get_ajax(jsonArr); } function get_ajax(jsonArr){ $.ajax({ method: 'POST', url: $('#MyForm').attr('action'), data: {'data': JSON.stringify(jsonArr)}, success: function(response) { console.log(response) alert('success'); }, error: function(response) { console.error(response) alert('error'); } }); } Following has my .py file code. def get_seq_input(request): if request.method == 'POST': message = request.POST.get('data') print(message) print("this message") the result is [{"key":1,"reciever":"system"}] and None anyone have idea to getrid of this None? -
AttributeError when I'm running Celery worker
I'm trying to use celery for background process in my Django application. Django version is 1.4.8 and latest suitable celery version is 3.1.25. I use Redis as broker and backend, json as serializer. When I start the worker celery -A celery_app worker -l info I'm getting Attribute error 'unicode' object has no attribute 'iteritems' My settings.py file: BROKER_URL = 'redis://localhost' CELERY_RESULT_BACKEND = 'redis://localhost/' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_STORE_ERRORS_EVEN_IF_IGNORED = True celery_app.py: import sys from django.conf import settings from celery import Celery project_root = os.path.dirname(__file__) sys.path.insert(0, os.path.join(project_root, '../env')) sys.path.insert(0, os.path.join(project_root, '../')) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project') app.config_from_object('project.settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True) tasks.py: @celery_app.task def sample_task(x): return 'Test response' and that's how I run this task: sample_task.delay({'key': 'test'}) And I get the following error: File "/Users/user/project/venv/lib/python2.7/site-packages/redis/_compat.py", line 94, in iteritems return x.iteritems() AttributeError: 'unicode' object has no attribute 'iteritems' I tried to find the issue on the internet, tried to pass another params to task. I don't know how to debug celery process and could not find the solution by myself. Please help me -
Authentication Details Not Provided REST API POST Request
I'm posting to an API server and I'm getting the following reply: Server Response: {"detail":"Authentication credentials were not provided."} I'm writing the requests in Java and I'm not sure exactly why it's saying credentials were not provided. Here is a snippet of my code: hconn.setRequestProperty("Content-Type", "application/json"); hconn.setRequestProperty( "Accept", "application/json" ); if( urlconn instanceof HttpsURLConnection ) { String encoded = new String(Base64.getEncoder().encode( ( username + ":" + password).getBytes())); String auth = "Basic " + encoded; urlconn.setRequestProperty("Encoded Authorization", auth ); } Where hconn is of type HttpURLConnection This is the only relvant snippet that you guys need. Are there properties i'm missing to set here? I know the server response is from a Django framework but the documentation is not clear on spotting what IS required to prevent this. Any help appreciated. -
Both Celery and Celerybeat are running, but beat.log only shows "starting ..." and nothing happens
I'v already checked my code on local server and I'm sure everything is ok on my code. So it seems something is wrong on server configuration. I have a linux server (Ubuntu 16.04) and installed nginx, redis , ...Also I created configuration files for celery and celerybeat as below: /etc/init.d/celeryd /etc/default/celeryd /etc/init.d/celerybeat /etc/default/celerybeat I checked their status ,both of them are running but when I check beat.log it doesn't do anything and only shows 'starting ...' celeryd file: # Names of nodes to start CELERYD_NODES="worker" # Absolute or relative path to the 'celery' command: CELERY_BIN="/home/amirali/AwesomeApp/awesome_env/bin/celery" # App instance to use CELERY_APP="AwesomeApp" # Where to chdir at start. Where your manage.py is... CELERYD_CHDIR="/home/amirali/AwesomeApp" # Extra command-line arguments to the worker CELERYD_OPTS="--time-limit=300 -Ofair --concurrency=8" # Set logging level to DEBUG CELERYD_LOG_LEVEL="INFO" # %n will be replaced with the first part of the nodename. CELERYD_LOG_FILE="/var/log/celery/%n%I.log" CELERYD_PID_FILE="/var/run/celery/%n.pid" # Workers should run as an unprivileged user. # You need to create this user manually (or you can choose # a user/group combination that already exists (e.g., nobody). CELERYD_USER="celery" CELERYD_GROUP="celery" # If enabled pid and log directories will be created if missing, # and owned by the userid/group configured. CELERY_CREATE_DIRS=1 celerybeat file: File: /etc/default/celerybeat CELERYBEAT_LOG_LEVEL="info" # … -
Filtering nested related objects in Django
I have a fairly simple relationship with 3 models and having problems constructing a queryset that returns the results the way I need them. Models: class Book(models.Model): name = models.CharField() class CategoryLabel(models.Model): name = models.CharField() class Review(models.Model): user = models.ForeignKey(User) book = models.ForeignKey(Book) labels = models.ManyToManyField(CategoryLabel) rating = models.IntegerField() Now, the queryset results should be a list of Books that a specific user has written a review about. That's easily achievable by books = Book.objects.filter(review__user=user) The tricky part is that I need to output (via django rest framework serializer) a list of books, each of which contains a list of reviews only for the specified user, aggregated average rating (again, only for the specified user) and a set of distinct labels the reviews were tagged with. So something like this in JSON: [ "name": "Book1", "reviews": [ "review_id1", "review_id2" ], "average_rating": 3, "labels": [ "label_id1", "label_id2" ] ] What I've tried so far: Book.objects.filter(reviews__user=user) .annotate(average_rating=Avg("reviews__rating")) .annotate(labels=ArrayAgg("reviews__labels", distinct=True)) This does produce the format I need but it aggregates average rating over all reviews, not only the ones by the user and the same story with labels, it just includes all labels applied in all reviews... Any ideas how this can be …