Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rebuild mod_wsgi if additional packages are added to venv
Do Django mod_wsgi need to be rebuilt under Apache if additional packages are added to venv? After installing additional packages in python venv, Apache server crashed, it says that the packages are not found, although they are installed in venv. I use python==3.10, Django==4.2. -
"Cannot find reference 'TextFields' in '__init__.py'
I tried importing models from django.db . At first PyCharm could not recognize the django.db although I had already installed it using cmd so i installed it again in pycharm but I am still getting the error "Cannot find reference 'TextFields' in 'init.py' " Tried creating a new app in my project -
DJANGO REST API - How do I restrict user access to API?
So I’ve been putting together a REST API using William Vincent’s REST API’s with Django book. I have everything up and going according to the book but I’m a bit of a noob so I need some clarification from the pros. How can I restrict a user without a token from seeing certain information within my API? Created user with Token: i added authentication_classes = [TokenAuthentication] to class UserList thinking if a user is logged in with a token that logged in user would be able to access that information of my api but I get the below: When I remove authentication_classes = [TokenAuthentication], I get the below. All users are able to see my API and I don’t want that, I only want users with a Token to view my api. Any help is gladly appreciated! Thanks! Code below # api/views.py from django.contrib.auth import get_user_model from rest_framework import generics, permissions from rest_framework.authentication import TokenAuthentication from .serializers import UserSerializer # Display List View - User class UserList(generics.ListAPIView): queryset = get_user_model().objects.all() serializer_class = UserSerializer permission_classes = (permissions.IsAuthenticated,) authentication_classes = [TokenAuthentication] # api/serializers.py from django.contrib.auth import get_user_model from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields =('id', 'username', 'email',) … -
Capture and edit site url and use value in html django
Want to get the site url and parse the path down to the string input and then validate that string is in a django model table. What I have done so far works in that it will display the string entered, but do not know how to then use it to compare what is in the customuser model alias_name field. If it is in the table, it should render the from in the template, if not, then it should render Sorry not found. FYI - I am new to this and have done my due deligence it resarching this. app/urls.py path('signup/str:alias_name/', SignUpView.as_view(), name='accounts/signup.html'), This allows any string to be put in here and the page renders. app/views.py class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy("login") template_name = "registration/signup.html" model = CustomUserCreationForm app/forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ( "first_name", "last_name", "email", "cell", "username", 'password1', 'password2', 'alias_name', 'org', ) class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ( "first_name", "last_name", "username", "email", "cell", ) template <!DOCTYPE html> <html> <body> {% extends "base.html" %} {% block title %}Sign Up{% endblock %} {% block content %} <h2>Sign Up</h2> <p id="alias"></p> <script> document.getElementById("alias").innerText = window.location.pathname.toString().replace('/accounts/signup/', '').replace('/', ''); </script> <h1>Your … -
How to make Django respect locale when accessing localflavor?
I'm trying to apply multi-language support to a Django application, and I have the basic configuration working so I can set a language session key and automatically pull the correct translations for the each gettext call around all my field labels. However, I have some Ajax calls that populate fields for country/state/province names, pulling data from the django-localflavor package, which includes full translation support. However, when I return, say, localflavor.jp.jp_prefectures.JP_PREFECTURES in my JSON response, even though my language session key is set to Japanese, and the values in that dictionary are wrapped with gettext, the values returned are in English, not Japanese. My Ajax view looks something like: from localflavor.jp.jp_prefectures import JP_PREFECTURES def get_country_states(request): lang = request.session.get('l', 'en') code = request.GET.get('code') if code == 'jp': states = {k: str(v) for k, v in JP_PREFECTURES} elif code == ... handle other cases return HttpResponse(json.dumps({'states': states})) How do I ensure str(v) renders the correct translated value based on the current language l session setting? I thought this happened automatically? Even though the values in JP_PREFECTURES are gettext instances, if I try and return them directly in the JSON response, I get the error: Object of type __proxy__ is not JSON serializable -
Django left join with filtered relation in QuerySet for ListView
I am a Django/Python novice. I am developing a website to help me manage a small golf society. A major function of the website is to enable members to view and book their place on upcoming events. The EventListview will display details for each event, including the venue(s) used by each event. It will also allow the member to Make/View/Modify/Cancel a booking for each event. All of this functionality is working apart from displaying the venue(s) for each event in the EventListView. members.models.py class Member(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) handicap = models.IntegerField(null=True, blank=True) etc ........ events.models.py class Venue(models.Model): name = models.CharField(max_length=64) description = models.TextField(max_length=256, null=True, blank=True) etc ........ class Event(models.Model): name = models.CharField(max_length=64) details = models.CharField(max_length=256) start = models.DateField(null=True, blank=True) finish = models.DateField(null=True, blank=True) etc ........ def get_venues(self): return mark_safe("<br />" . join([x.venue.__str__() for x in self.venue.all()])) class Event_Venue(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='venue') venue = models.ForeignKey(Venue, on_delete=models.CASCADE, related_name='event') etc ........ class Member_Event(models.Model): member = models.ForeignKey('members.Member', on_delete=models.CASCADE, related_name='booking') event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='booking') etc ........ events.views.py class EventListView(LoginRequiredMixin, ListView): model = Event context_object_name = 'event_list' paginate_by = 8 template = 'events/event_list.html' def get_queryset(self): return Event.objects.annotate(booked=FilteredRelation('booking', condition=Q(booking__member=self.request.user.member))).values('id', 'name', 'details', 'start', 'finish', 'currency', 'price', 'status', 'booked__member') event_list.html . . . {% if … -
Django All-Auth with Djongo (PyMongo)
I've created a Django project that uses the Djongo plugin to connect to a MongoDB instance. All works well with Djongo, however, now that I am trying to implement all-auth, there are some problems. Upon logging in (using the default all-auth process and clicking Google), I get this DatabaseError. It doesn't really give any exception, but my theory is that I need to create a User model that uses the Djongo model, which I've been unsuccessful in doing. Has anybody done a similar setup that can help? Run this branch here (directions in README.md, however you will need a google OAUTH credential) to replicate the problem https://github.com/bens-schreiber/pushapp-2023/tree/schreiber/all-auth/backend -
I can't prepare multiple databases in Django (sqlite3)
There is a problem which I can't understand how that happens. First let me clear what do I want: Use a database called sol_data.sqlite3 for two models: SolModel1, SolModel2 (These models defined in an app called sol_app) Use a database called db.sqlite3 for any other models like always (Django built-in models and other apps) It's obvious db.sqlite3 should not include SolModel1 and 2. and sol_data.sqlite3 should only include SolModel1 and 2 tables. But when I migrate, both tables have all django models, and sol_data.sqlite3 have SolModel1 and 2 addition to them. I'm confused. (I read the docs: https://docs.djangoproject.com/en/4.2/topics/db/multi-db) My code settings.py ... # other settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, "sol_data_db": { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'sol_data_db.sqlite3', } } DATABASE_ROUTERS = ["sol_app.dbrouters.SolDataRouter"] ... # other settings sol_app/dbrouters.py class SolDataRouter: def db_for_read(self, model, **hints): if model._meta.app_label == "sol_app": return "sol_data_db" return None def db_for_write(self, model, **hints): if model._meta.app_label == "sol_app": return "sol_data_db" return None def allow_relation(self, obj1, obj2, **hints): if (obj1._meta.app_label == "sol_app" and obj2._meta.app_label == "sol_app"): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == "sol_app": return db == "sol_data_db" else: return None my terminal ➜ python manage.py … -
The view App.views.login_view didn't return an HttpResponse object. It returned None instead
def login_view(request): if request.method == 'POST': form = AuthenticationForm(request.POST) if form.is_valid(): user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password']) if user != None: auth_login(request, user) return redirect('home') else: return redirect('login') else: form = AuthenticationForm() context = { 'form': form, } return render(request, "login.html", context) Its not redirecting me 404.html page or home.html page for that matter this the error i am getting I using "auth_user" database also my urls are configured properly Request Method: POST Request URL: http://127.0.0.1:8000/login/ Django Version: 4.2.5 Exception Type: ValueError Exception Value: The view App.views.login_view didn't return an HttpResponse object. It returned None instead. -
I wrote the first project from the Django site, it does not issue an error, but when I go to the browser, it only shows the picture of the rocket
enter image description here I imported the code from the first Django site project and expected the Django function codes to run in the browser, but they all show rocket images. Do I need to install a specific item or program? -
unwanted line break in flex box
i have a flex container 'elements' (direction column) and im trying to add items to it using js script: // Generate and append the inner elements for (var j = 0; j < 3; j++) { var innerDiv = document.createElement('div'); innerDiv.textContent = '3/12'; //this works elements.appendChild(innerDiv); } when the textContent is normal there is no problem, i get 3 lines no matter how long the text is. but when i try to enter (as it seems) 2 specific characters together one after another like innerDiv.textContent = '[i][j]'; //i get [i] and [j] in seperated lines innerDiv.textContent = '1/√5'; //i get 1/ and √5 in seperated lines and end up with twice the rows. i tried to make sure its a string, didnt work. also it doesnt have anything to do with the style i checked. thanks for the help! -
Filtering in the dictionary list for the jsonfield in Django
I have a django model that uses postgres json column. class ClassName(models.Model): data=JsonField(default=dict,blank=True,null=True,) This is the schema in the json field. { "name": "foo", "thing":[ { "id": "1", "key": "hello" }, { "id": "2", "key": "world" } ] } Is it possible to search against one key value in the list of dictionaries using ILIKE (icontains) operator? ClassName.objects.filter(data__thing__key__icontains="wo") Maybe someone has faced this problem? I will be glad of any considerations ClassName.objects.filter(data__thing__contains=[{'key':'world'}]) - works (but only contains) ClassName.objects.filter(data__thing__1__key__icontains='wo') - works (but only with the indication of the element) -
Problem with dockerizing a Django project with Celery and RabbitMQ
I am trying to dockerize my Django project with Celery and RabbitMQ. I have a Docker Compose file, but I am having trouble getting it to work. Here is my Docker Compose file: services: rabbitmq: image: rabbitmq:latest networks: - main ports: - "5672:5672" restart: always environment: - RABBITMQ_DEFAULT_USER=guest - RABBITMQ_DEFAULT_PASS=guest celery_worker: image: python:3.10 command: celery -A zwitter worker -l INFO build: context: . depends_on: - app - rabbitmq environment: - CELERY_BROKER_URL=amqp://guest:guest@rabbitmq:5672/ networks: - main restart: always redis: image: redis:latest ports: - "6379:6379" volumes: - cache:/data command: redis-server --save 60 1 restart: always app: image: python:3.10 build: . command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/src/ ports: - "8000:8000" networks: main: volumes: cache: When I try to start the Docker Compose containers, everything works fine and the containers are all up. But when any celery task is about to run in my django project, I get the following error: [Errno -3] Temporary failure in name resolution I have tried all of the following, but the problem still persists: Making sure that the RabbitMQ server is running and accessible. Making sure that the Celery worker is configured to connect to the correct … -
Django sessions are merging
i am creating a cloud with django, I am using email id as my primary key for storing user files,The problem is when i am going to uploaded files (my files section) by getting the uploaded files by filtering them with email id (getting the email from session from login page)it sorting the files properly.but if a other user using the page at the same time the sessions are merging when the user1 refreshes his page and the user 1 can see the files of user 2 lead into security issues... help me to solve this (i dont want to post the my code here) if you really need to help me DM gmail(thangamuthukkudi2015@gmail.com) or my number whatsapp or sms (+91 6380811676) i tried creating two individual sessions to prevent overiding but it didn't work pls help.... or give me some ways to transport the email id without use of sessions -
Django app runing on Azure Web App + Database PostgreSQL - csrf error
My application is running on Azure, but I get a csrf error on the login page. And yet: My template has the {% csrf_token %} within the element: I have 'django.middleware.csrf.CsrfViewMiddleware', in the MIDDLEWARE definition in settings.py. In addition, you have to know that the same code (besides the migration required by the PostgreSQL usage) is running on another Azure instance with sqlite and is working correctly. As I am a newbie in Azure and web developmeent, any hint is welcome. Best regards -
This happens when i run makemigrations or migrate in django, How do i solve this error?
I'm trying to run makemigrations in my django project, but I get an unsolvable error. My os is fedora 38 and im using vscode this only happens when I'm using postgress database(online). but my code runs fine on sqlite3 database. you can see the error below when I use makemigrations command: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? warnings.warn( No changes detected And when I use migrate command this error happens: Traceback (most recent call last): File "/home/arad/Django/store_project/.venv/lib64/python3.11/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection self.connect() File "/home/arad/Django/store_project/.venv/lib64/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ . . . File "/home/arad/Django/store_project/.venv/lib64/python3.11/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/arad/Django/store_project/stationary_store/manage.py", line 22, in <module> main() File "/home/arad/Django/store_project/stationary_store/manage.py", line 18, in main execute_from_command_line(sys.argv) . . . File "/home/arad/Django/store_project/.venv/lib64/python3.11/site-packages/psycopg2/__init__.py", line 122, in … -
django cannot connect to the database on the server
I have deployed the project and an error occurred Watching for file changes with StatReloader Performing system checks... `System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/django/db/backends/base/base.py", line 289, in ensure_connection self.connect() File "/usr/local/lib/python3.10/dist-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/django/db/backends/base/base.py", line 270, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.10/dist-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/django/db/backends/postgresql/base.py", line 275, in get_new_connection connection = self.Database.connect(**conn_params) File "/usr/local/lib/python3.10/dist-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: fe_sendauth: no password supplied The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.10/dist-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/django/core/management/commands/runserver.py", line 136, in inner_run self.check_migrations() File "/usr/local/lib/python3.10/dist-packages/django/core/management/base.py", line 574, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/usr/local/lib/python3.10/dist-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python3.10/dist-packages/django/db/migrations/loader.py", line 58, in __init__ self.build_graph() File "/usr/local/lib/python3.10/dist-packages/django/db/migrations/loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/local/lib/python3.10/dist-packages/django/db/migrations/recorder.py", line 81, in applied_migrations if self.has_table(): File "/usr/local/lib/python3.10/dist-packages/django/db/migrations/recorder.py", line 57, in has_table with self.connection.cursor() as cursor: File "/usr/local/lib/python3.10/dist-packages/django/utils/asyncio.py", … -
Django and Mongo db
BooleanField gives back Database Error and no exception message supplied. I tried using 'integer value with 0 and 1, char value with yes and no and researched every issues but still no answers or solutions. In my Website i can't seem to change the is_sold to yes or no as a client which is probably due to the mongo db issues or limitation or its nature. here is the error image ] from django.contrib.auth.models import User from django.db import models from djongo import models class Category(models.Model): name = models.CharField(max_length=255) class Meta: ordering = ('name',) verbose_name_plural = 'Categories' def __str__(self): return str(self.name) class Item(models.Model): category = models.ForeignKey(Category, related_name='items', on_delete=models.CASCADE) name = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) price = models.FloatField() image = models.ImageField(upload_to='item_images', blank=True, null=True) # is_sold = models.BooleanField(default=False) published_by = models.ForeignKey(User, related_name='items', on_delete=models.CASCADE) published_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.name) -
Images not getting displayed on Apache server
Error Screenshot I built a website using the Django framework and hosted it on an Apache server. The images are not getting displayed for some reason. It is giving me a 404 error (please see the attached image) but I am sure it is looking at the right place. However, it is fetching other sorts of files like csv but not images. Also, when I run it on a local server, the images are getting displayed. Can someone please help me out? I tried to change the way I am specifying the path but it is still not working (please see the attached images).Code Part-1 Code Part-2 Code Part-3 -
How to get APPEND_SLASH to work properly with nginx rewrite?
I have this in nginx config location /todjango/ { rewrite ^/todjango(/.*)$ $1 break; uwsgi_pass django; In urls.py urlpatterns = [ path("foo/", include("foo.urls")) ] APPEND_SLASH is True by default When I type curl http://localhost:8000/todjango/foo I want to get 301 to /todjango/foo/, but instead I get 301 to /foo/. When APPEND_SLASH is False I get 404 as expected -
How can I change this model for multiple choice answer?
I am making a Django app for multiple choice question-answer exam. I have created a Question model as below. class Question(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) question_name = models.CharField(max_length=200,null=True) option1 = models.CharField(max_length=200,null=True) option2 = models.CharField(max_length=200,null=True) option3 = models.CharField(max_length=200,null=True) option4 = models.CharField(max_length=200,null=True) answer = models.CharField(max_length=200,null=True) def __str__(self): return self.question_name It is working fine, but now I want to change it so that question can have more that one option as correct answer. How can I achieve it? I will be adding the questions for my app from admin panel. I want to add quesion , their options and then mark the right answer/answers (it is possible to) otherwise make a field that can hold the right answer/answers Is there any way to make a field both CharField and BooleanField ? Or what approach should I take to complete my goal ? Thanks in advance for the suggestions!! :) -
How can I inline a Form of a OneToOne Relation
I have the following django models where a OneToOne Relation is used. Models: class ClientCustomFields(models.Model): some_custom_id = models.CharField(max_length=36, blank=True, null=True) # .... more custom fields class Client(ExternalIdModel): first_name = CharField(max_length=200) last_name = CharField(max_length=200) Now, since this is an easy 1:1 relation, I want to embed the form of the custom fields directly into the form of the customer. But I am having troubles stitching the Forms together. class ClientCustomFieldsForm(ModelForm): class Meta: model = ClientCustomFields fields = '__all__' class ClientForm(ModelForm): custom_fields = ClientCustomFieldsForm() class Meta: model = Client fields = '__all__' I have tried a couple of others like BaseInlineFormSet but without any luck so far. Although there is a similar question here on SO, this however, is admin related and at least I could not figure out how this could help me. -
is there a way for optimize this piece of code?
I have these two model below: models.py file: class Profile(models.Model): """ User Profile Model This model represents a user's profile information, including their avatar, location, city, address, and geographical coordinates (latitude and longitude). Fields: - user (OneToOneField): The associated user instance. - avatar (ImageField): An optional user avatar (profile picture). - location_picture (ImageField): An optional picture of the user's location. - city (CharField): An optional field for the user's city. - address (CharField): An optional field for the user's address. - latitude (DecimalField): An optional field for the latitude of the user's location. Valid range: -90.0 to 90.0. - longitude (DecimalField): An optional field for the longitude of the user's location. Valid range: -180.0 to 180.0. """ user = models.OneToOneField( settings.AUTH_USER_MODEL, verbose_name=_("User"), help_text=_("the profile of a user instance."), db_comment=_("the profile of a user instance."), on_delete=models.CASCADE ) city = models.CharField( verbose_name=_("City"), help_text=_("'Optional'.this is the city of the user."), db_comment=_("'Optional'.this is the city of the user."), max_length=255, null=True, blank=True ) address = models.CharField( verbose_name=_("Address"), help_text=_("'Optional'.this is the address of a user."), db_comment=_("'Optional'.this is the address of a user."), max_length=255, null=True, blank=True ) shair_location = models.BooleanField( verbose_name=_("Shair Location"), default=False, help_text=_("'Optional.thie mean you want to shair your location or not!'"), db_comment=_("'Optional.this mean you want … -
How to pass dictionary data to chart.js in django?
I want to get a report by chart from my model but I can't figured out how to pass data from a dictionary to chart using chart.js? here is my model: class Book(models.Model): number = models.CharField(_("number"), max_length=255) title = models.CharField(_("title"), max_length=255) subtitle = models.CharField(_("subtitle"), max_length=255, null=True,) authors = models.TextField(_("authors"), null=True,) publisher = models.CharField(_("publisher"), max_length=255, null=True,) published_date = models.DateField(_("published date"), null=True,) category = models.CharField(_("category"), max_length=255, null=True,) distrubution_expense = models.FloatField(_("distribution expense")) def __str__(self): return self.title def get_absolute_url(self): return reverse('book_detail', args=[str(self.id)]) and this is my view that I use queryset to count the number of categories repetition: class CategoryChartListView(generic.ListView): model = Book template_name= 'pages/chart_category.html' def get_context_data(self, **kwargs): context = super(CategoryChartListView, self).get_context_data(**kwargs) context["dictCategory"] = Book.objects.values('category').annotate(count=Count('category')) return context also this is the dictionary that I get from above queryset in view: {'category': 'Business Analytics', 'count': 336} {'category': 'Data ethics', 'count': 389} {'category': 'visualization', 'count': 314} {'category': 'statistics', 'count': 428} {'category': 'NLP', 'count': 368} {'category': 'Language', 'count': 1} {'category': 'python', 'count': 373} {'category': 'maths', 'count': 379} {'category': 'deep learning', 'count': 364} {'category': 'SQL', 'count': 403} {'category': 'Python', 'count': 80} {'category': 'R Studio', 'count': 246} {'category': 'data science', 'count': 395} {'category': None, 'count': 0} and template: {%block content%} <!-- displaying the chart --> <!-- you can also … -
Django Queryset: iterate through nested array of objects in JSONField using annotation and F expressions
In my Django 4.2 project, I have a model with some JSONField (using PgSQL and the DB backend), e.g. from django.db import models class MyModel(models.Model): my_json = models.JSONField(null=True, blank=True) ... And model instances contain nested arrays of JSON objects, e.g. { "members":[ { "name": "Person #1", "age": 41 }, { "name": "Person #2", "age": 51 } ], "other_data": ... } While obtaining MyModel instances from the DB, I'd like to simplify the content to be returned later in the View, so that I don't return complete array of members objects (for each model instance) but only an array of string (their names). I.e. instead of returning content like: [ { "members":[ { "name": "Person #1.1", "age": 41 }, { "name": "Person #1.2", "age": 51 } ], "other_data": ... }, { "members":[ { "name": "Person #2.1", "age": 42 }, { "name": "Person #2.2", "age": 52 } ], "other_data": ... }, ... ] I'd actually like to return: [ { "member_names":["Person #1.1", "Person #1.2"], "other_data": ... }, { "member_names":["Person #2.1", "Person #2.2"], "other_data": ... }, ... ] I'd like to use Django queryset annotation to introduce member_names property above, which would summarize the name properties from related members array (of each model …