Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: module 'django.db.models' has no attribute 'get_models'
why am i getting issue when calling for get_model() function? Here is what I am trying to do @classmethod def get_content_models(cls): """ Return all Package subclasses. """ is_content_model = lambda m: m is not Package and issubclass(m, Package) return list(filter(is_content_model, models.get_models())) This used to work before but now after updating to new django, it's throwing an error. How can this be resolved? -
Heroku/Django - Cannot find Postgresql db
When I am running my server in heroku, I get this error saying: Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? On my heroku app, it says that it does have a Postgres db addon added. -
How to interpret this parsing error of the image variable that was rendered in the django template in heroku?
The error says (ImageFieldFile' object is not subscriptable) I wanted to call an image url using an image variable in the html django templates. I thought it was a date-util version error as i have been seeing other users recommend using date-utl version 1.5 which heroku only works with even after deprecating the date-util 2.8 to v 1.5 it still didnt work. SyntaxError at / invalid syntax (parser.py, line 158) this is where the error occured src="{{ tweet.user.profile.image.url }}" Error was this SyntaxError at / invalid syntax (parser.py, line 158) Request Method: GET Request URL: https://meawesometwitterapp.herokuapp.com/ Django Version: 2.2.2 Exception Type: SyntaxError Exception Value: invalid syntax (parser.py, line 158) Exception Location: /app/.heroku/python/lib/python3.7/site-packages/botocore/credentials.py in , line 27 Python Executable: /app/.heroku/python/bin/python Python Version: 3.7.3 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python37.zip', '/app/.heroku/python/lib/python3.7', '/app/.heroku/python/lib/python3.7/lib-dynload', '/app/.heroku/python/lib/python3.7/site-packages'] Server time: Mon, 29 Jul 2019 09:32:44 +0000 I cant intepret the error in the production heroku django app -
Django annotate count doesn't work always return 1
My models: class PicKeyword(models.Model): """chat context collection """ keyword = models.TextField(blank=True, null=True) Myfilter: from django.db.models import Count PicKeyword.objects.annotate(Count('keyword'))[0].keyword__count The result always get 1 just like: print(PicKeyword.objects.filter(keyword='hi').count() show: 3 PicKeyword.objects.filter(keyword='hi').annotate(Count('keyword'))[0].keyword__count show: 1 Is it because I use sqllite or my keyword type is Textfield? -
Change admin form name for overridden User
I've overridden the standard django User by extending AbstractUser. Now this all works fine, but for some reason I can't make the admin display "Profiles" (the name of the model now set in settings.AUTH_USER_MODEL instead of "Users". This is my code for admin.py for the profiles app from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserChangeForm from .models import Profile class ProfileChangeForm(UserChangeForm): class Meta(UserChangeForm.Meta): model = Profile verbose_name_plural = "Profile" class ProfileAdmin(UserAdmin): form = ProfileChangeForm # fieldsets = UserAdmin.fieldsets + ((None, {"fields": ("some_extra_data",)}),) fieldsets = UserAdmin.fieldsets admin.site.register(Profile, ProfileAdmin) I'd figured there should be some Meta setting I can put in here, but after significant amounts of googling I can't find anything. I'm sure this is a simple answer - could somebody point me in the right direction? I've tried setting "name" and "verbose_name", but no joy. At the end of the day, I could live with this, as it's just the admin interface, but it's bugging me ... -
How can I change fieldsets from BaseAdmin model? Unhashable type: 'list'
I decided to create a basic model for admin panel, from which I will inherit. It has fieldsets. How can I insert certain fields into the first and second tuples? Found the get_fieldsets method. But for now, I get an error. TypeError: unhashable type: 'list' admin.py class BaseCreditAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'slug', 'created_at', 'updated_at'] list_display_links = ['slug',] fieldsets = [ (None, {'fields': [['best', 'hot'], 'name', 'slug']}), ('SEO', {'fields': [['breadcrumbs',], ['meta_title',], ['meta_keywords',], ['meta_description',],['short_description',],]}) ] model = AbstractBaseProduct Tracebck: Unhandled exception in thread started by <function wrapper at 0x7f799fddb1b8> Traceback (most recent call last): File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/contrib/admin/apps.py", line 22, in ready self.module.autodiscover() File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/m0nte-cr1st0/work_projects/startup/finbee/credits/admin.py", line 60, in <module> admin.site.register(Credit, CreditAdmin) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 109, in register system_check_errors.extend(admin_obj.check()) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 113, in check return self.checks_class().check(self, **kwargs) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/contrib/admin/checks.py", line 495, in check errors … -
Determining the number of connected clients in django channels 2
for a webrtc project, I need to transform the server code from https://codelabs.developers.google.com/codelabs/webrtc-web/#6 to a django channels 2 version. In the code, as you can see, the server sends/emits some events based on the number of clients connected. here is the code: 'use strict'; var os = require('os'); var nodeStatic = require('node-static'); var http = require('http'); var socketIO = require('socket.io'); var fileServer = new(nodeStatic.Server)(); var app = http.createServer(function(req, res) { fileServer.serve(req, res); }).listen(8080); var io = socketIO.listen(app); io.sockets.on('connection', function(socket) { // convenience function to log server messages on the client function log() { var array = ['Message from server:']; array.push.apply(array, arguments); socket.emit('log', array); } socket.on('message', function(message) { log('Client said: ', message); // for a real app, would be room-only (not broadcast) socket.broadcast.emit('message', message); }); socket.on('create or join', function(room) { log('Received request to create or join room ' + room); var clientsInRoom = io.sockets.adapter.rooms[room]; var numClients = clientsInRoom ? Object.keys(clientsInRoom.sockets).length : 0; log('Room ' + room + ' now has ' + numClients + ' client(s)'); if (numClients === 0) { socket.join(room); log('Client ID ' + socket.id + ' created room ' + room); socket.emit('created', room, socket.id); } else if (numClients === 1) { log('Client ID ' + socket.id + ' … -
gunicorn keeps rebooting it's worker when Django is starting Python project
I am running a web-based project with a data science focussed backend which is hosted on a Microsoft Azure cloud server. Large deep learning models need to be loaded and initialized when Django starts the project. I am running the project through an nginx server which communicates to the Django server through gunicorn. If I run the project on the same Azure cluster through Django alone (not using nginx or gunicorn) it initializes and starts just fine. However, when I run it on nginx through gunicorn, one of the workers keeps rebooting as the project is starting up (it takes maybe ~2 mins to initialize. Here is the output from the gunicorn command when I try to start the Django project: user@host:/home/libor/libor_transition/libor_transition_api$ sudo gunicorn --pythonpath="$(pwd)" --log-level=DEBUG -t 1000 libor_transition_api.wsgi:appli> [2019-07-29 08:43:44 +0000] [33808] [DEBUG] Current configuration: config: None bind: ['127.0.0.1:8000'] backlog: 2048 workers: 1 worker_class: sync threads: 1 worker_connections: 1000 max_requests: 0 max_requests_jitter: 0 timeout: 1000 graceful_timeout: 30 keepalive: 2 limit_request_line: 4094 limit_request_fields: 100 limit_request_field_size: 8190 reload: False reload_engine: auto reload_extra_files: [] spew: False check_config: False preload_app: False sendfile: None reuse_port: False chdir: /home/libor/libor_transition/libor_transition_api daemon: False raw_env: [] pidfile: None worker_tmp_dir: None user: 0 group: 0 umask: 0 initgroups: False … -
How to set a timedelta in between two model datefields
i'm strugling some time already trying to set a timedelta in two fields of my model, then display de difference between then. i've tried Stack and a lot of others tutorials and not quite shure if a should make a function on my models or my views, or a basic variable on the views i've tried all of them here is my code: MODELS.PY from django.db import models from datetime import datetime from datetime import timedelta class To_do (models.Model): task = models.CharField(max_length=150) topic = models.CharField(max_length=150) how = models.TextField(max_length=600) start = models.DateField(blank=False) end = models.DateField(blank=False) def __str__(self): return self.task VIEWS.PY class DetailView(DetailView): template_name = 'details.html' model = To_do def get_queryset(self): return To_do.objects.all() def get_delta(self): d1 = To_do.start d2 = To_do.end tdelta = d1-d2 return tdelta i want to display the difference between the star and end and after that, and after that setup an alarm if get less than three days. appreciate your help. -
User authentication using django and MYSQL
i am trying to authenticate the user using MYSQL (running on XAMPP). however the table in the database has been created but when i manually add a user and password in database and then try to authenticate then it show invalid credentials. the above thing has been succesfully done using sqlite3 Objectives to be achieved :- A) User authentication using MYSQL B)Everytime the user log-in, In database the name and datetime of the user login should be reflected. Here's code:- models.py from django.db import models from datetime import datetime from django.contrib.auth.models import AbstractUser # Create your models here. class Login(AbstractUser): username = models.CharField(max_length=50,blank=False) password = models.CharField(max_length=32) def __str__(self): return self.username Views.py from django.shortcuts import render from first_app.forms import CmdForm #view after login from django.http import HttpResponse, HttpResponseRedirect #some imports from django.urls import reverse import csv from django.contrib.auth import authenticate,login,logout from django.contrib.auth.decorators import login_required from django.contrib import messages #from django.contrib.sessions import serializers # Create your views here. def login_view(request): context = {} if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user: login(request, user) return HttpResponseRedirect(reverse('IP form')) else: messages.error(request,'Please provide valid credentials') return render (request,"first_app/login.html", context) else: return render (request,"first_app/login.html", context) @login_required def user_logout(request): … -
IF statement not working with list difference
Trying to get the result of the difference between two list, using below code, but doesn't seemed to work, Please help list1 = ['one', 'two', 'three'] list2 = ['one', 'two', 'three', 'four'] list3 = list(set(list1) - set(list2)) if not list3: #if not empty, print list3 print(list3) else: # if empty print none print("None") -
I keep getting a 404 error when django is looking for static files
I keep getting a 404 error when django is looking for static files. settings.py STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn') STATIC_URL = '/static_cdn/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) project tree structure of app - business -- migrations --- .... -- static --- business ---- main.css ---- scripts.js -- templates --- business ---- base.html ---- home.html -- templatetags --- ... -- __init__.py -- admin.py -- apps.py -- models.py -- tests.py -- urls.py -- views.py Error [29/Jul/2019 13:09:45] "GET / HTTP/1.1" 200 12670 [29/Jul/2019 13:09:45] "GET /static_cdn/business/main.css HTTP/1.1" 404 77 [29/Jul/2019 13:09:45] "GET /static_cdn/business/scripts.js HTTP/1.1" 404 77 I also link to static files like {% static 'business/main.css' %} and I do have {% load static %} at the top of my document. Why isn't django able to find the static files? The error says it is looking in the correct place but it is returning 404 error. If you need anything else, you can look at my code -
Overwriting nested serializer's create method throws TypeError: create() got multiple values for keyword argument
I want to send data to my API. My data structure is nested. So I am trying to overwrite the create method following the docs and SO. When sending data it gives me the following error: TypeError: create() got multiple values for keyword argument 'graph' My data structure looks like this: { "project": "project1", "name": "Graph1", "description": "Graph belongs to Projekt1", "nodes": [ { "id": 2, "name": "Node1 of Graph 1", "graph": 3 } ] } Her is what I am trying in my serializer (which is pretty standard I assume): class GraphSerializer(serializers.ModelSerializer): nodes = NodeSerializer(many=True) class Meta: model = Graph fields = ('project', 'name', 'description', 'nodes', ) def create(self, validated_data): nodes_data = validated_data.pop('nodes') graph = Graph.objects.create(**validated_data) print(graph) for node_data in nodes_data: Node.objects.create(graph=graph,**node_data) return graph The error is in the for loop. When I debug though and print graphit give me back just one Graph (Graph1). So I don't understand why I should get a multiple values error. Here is more info if needed: Node serializer class NodeSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) class Meta: model = Node fields = ('id', 'name', 'graph', ) My models class Graph(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=120, blank=True) description = models.CharField(max_length=400, blank=True) def __str__(self): … -
allowing spaces and numbers in Django fields
I want to allow spaces and numbers in the field, I changed the form forms.CharField to forms.RegexField and it didnt work. I found similar questions: Here, Here and other questions, but none of them works good. alphanumeric_underscore = RegexValidator(r'^[0-9a-zA-Z]*$') list_of_templates = get_template_database_names() existing_database = forms.ModelChoiceField( queryset=TemplateDatabase.objects.all(), label='Name des Templates') new_database = forms.CharField(label='Name von Datenbank ' 'auf Basis des Templates', max_length=255, validators=[alphanumeric_underscore]) I can use numbers in the name, but it cannot begin or end with numbers. but by using space its not working -
django 2.2.3-Django 404 error ('Page not found') after runserver
My project is named 'tweetme', and when I runserver I get this error. Using the URLconf defined in tweetme.urls, Django tried these URL patterns, in this order: ^admin/ ^static/(?P<path>.*)$ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. urls.py file: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), ] if settings.DEBUG: urlpatterns += (static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)) I expect to shows: the install worked successfully! Congratulation but its shows me: Page not found at/ -
Return data based on model flag for OnetoOne Nested Serializer
I am using a nested serializer for onetoone mapping for a model offer. But i want the nested serializer to only return data if the fllag in the model instance of nested serializer is set to true. I guess to_representation will not work here as it will receive an object instance rather than queryset. Model : class Offers(models.Model) : brand = models.CharField(max_length=100,blank=True,null=True) hospital = models.OneToOneField('hospital.Providers',to_field='hospital_id',on_delete=models.SET_NULL, related_name='hospital_offer',blank=True,null=True) validity = models.PositiveIntegerField(default=0) terms = models.CharField(max_length=500,blank=True,null=True) discount = models.PositiveIntegerField(default=0) logo = models.CharField(max_length=100,blank=True,null=True) active = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) Serializer : class ProviderOffersSerializer(serializers.ModelSerializer) : class Meta : model = Offers fields = ('brand','id') class ProviderSerializer(serializers.ModelSerializer): hospital_offer = ProviderOffersSerializer(read_only=True) network = NetworkSerializer(read_only=True) class Meta: model = Providers fields = ('hospital_id','hospital_name','hospital_offer','pincode','network') Now ProviderSerializer should return data for offer only if active is True. Any help will be appreciated. -
Django. When adding an image, create a folder corresponding to the object id
I created a model, it has a line for the image: photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) In the example, if I add an image, a folder is created with the date of adding I wish that when add an image, create a folder with the "id" of the object. Please tell me the solutions! Thanks and sorry for my english! -
Please Help me to fix this issue
I'm learning python Django. I have been trying to create a custom user model and it is working but the issue I have is that whenever I visit any user's profile through the Django admin I get this error Exception Value: 'date_joined' cannot be specified for UserProfile model form as it is a non-editable field. Check fields/fieldsets/exclude attributes of class UserAdminModel. Here is how my model is looking like. class UserProfile(AbstractBaseUser, PermissionsMixin): """ A model for authors and readers.""" first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) username = models.CharField(max_length=255, unique=True) email = models.EmailField(max_length=255, unique=True) password = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) REQUIRED_FIELDS = ['email', 'password'] USERNAME_FIELD = 'username' objects = UserProfileManager() def __str__(self): return self.username also my serialiser looks like this class UserProfileSerializer(ModelSerializer): """ Serializers user profile model. """ def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class Meta: model = UserProfile fields = ('id', 'first_name', 'last_name', 'username', 'email', 'is_staff', 'password') extra_kwargs = { "is_staff": { "read_only": True }, } -
Django CMS multi-line field
Is it possible to make multi-line field on this page, because it's really uncomfortable when you have to scroll to see the whole thing. -
PyCharm not recognizing models
I am writing unit tests for my project but when I run tests file it says apps.products.models.Category.DoesNotExist: Category matching query does not exist. and it does not recognize in tests.py file. Though I have already included installed apps in the settings PROJECT_APPS = [ 'apps.core', 'apps.products ', ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'django_filters', ] + PROJECT_APPS I am importing like this from apps.products.models import Category and that model is not detected I have init file in my directory. Any help please) -
How to override the field value for modelformset in CreateView?
I use different qwerysets for modelformset of the same model. The first filter for grouping values from queryset I define in forms.py class SkillCreateFrameworkForm(SkillBaseCreateForm): def __init__(self, *args, **kwargs): super(SkillCreateFrameworkForm, self).__init__(*args, **kwargs) self.fields['technology'].queryset = Technology.objects.filter(group__name="Framework") class SkillCreatePLanguageForm(SkillBaseCreateForm): def __init__(self, *args, **kwargs): super(SkillCreatePLanguageForm, self).__init__(*args, **kwargs) self.fields['technology'].queryset = Technology.objects.filter(group__name="Programming language") The next step is to filter out the values that are already bound to the user being edited. To do this, in get_context_data I get a list of all the technologies that the user already has. employee_current_technology = Technology.objects.filter(skill__employee__id=self.kwargs['pk']) get_context_data def get_context_data(self, **kwargs): context = super(SkillTestCreateView, self).get_context_data(**kwargs) employee_current_technology = Technology.objects.filter(skill__employee__id=self.kwargs['pk']) context['formset_framework'] = SkillFrameworkFormSet() context['formset_planguage'] = SkillPLanguageFormSet() context['tech_group'] = Techgroup.objects.all() return context How do I now apply a filter to context['formset_framework'] that excludes technologies that the user already has? Smt like context['formset_framework'] = SkillFrameworkFormSet().field['technology'] not in employee_current_technology <-- ??? -
how to process submit on django-tables2 with a class View with FilterView mixin
I have a django-tables2 FilterView. The filter is templated in a form: {% if filter %} <form action="" method="get" class="form form-inline"> {% bootstrap_form filter.form layout='inline' %} {% bootstrap_button 'filter' %} </form> {% endif %} I have added a checkbox field to each row, and I have the table in a form: <form action="table_selection" method="get" class="form form-inline"> {% csrf_token %} {% render_table table 'django_tables2/bootstrap.html' %} <button class="btn btn-primary red" type="submit" >Submit Rows</button> </form> When I submit, I get logging messages like: GET /three_pl/threepl_fulfilments_filter/table_selection?csrfmiddlewaretoken=... &select_row=198&select_row=158&select_row=159 so the select_rows are very interesting. But I am lost with the class view, I can't grapple with how to process the form submission. This is my view: class FilteredThreePLFulfimentsView(SingleTableMixin,FilterView): table_class = ThreePL_order_fulfilmentsTable model = ThreePL_order_fulfilments template_name = "three_pl/ThreePLFulfilmentsFilter.html" #three_pl/templates/three_pl/ThreePLFulfilmentsFilter.html filterset_class = ThreePLFulfilmentsFilter -
how can i modified field is recorded, in django.form or django.model
I want to record the model field when they are be modified, who modifid them; the olg field and the new field. I do it in them ModelForm.clean, to find which field be modified, and record them. class SynthesisStepForm(BootstrapModelForm): class Meta: model = SynthesisStep fields = ('title', 'version', 'condition', 'yield_rate', 'testing', 'stype') widgets = { 'testing': forms.Textarea(attrs={'rows': '4', 'cols': '100', 'style': 'width:auto;'}), 'condition': forms.Textarea(attrs={'rows': '4', 'cols': '100', 'style': 'width:auto;'}) } def clean(self): """ :return: """ update_fields = ('title', 'version', 'condition', 'yield_rate', 'testing', 'stype') cleaned_data = super(BootstrapModelForm, self).clean() update_note = supervisory_update_fields(self, cleaned_data, update_fields) self._update_note = update_note return cleaned_data def supervisory_update_fields(form_obj, cleaned_data, update_fields): """ :param form_obj: :param cleaned_data: :param update_fields: :return: """ update_note = '' if form_obj.instance.pk: # new instance only changed_data = form_obj.changed_data for data in changed_data: if data in update_fields: try: old_field = eval('form_obj.instance.{0}'.format(data)) new_field = cleaned_data[data] if old_field != new_field: update_note = update_note + '{2} is modified , from "{0}" to "{1}"\n'.format(old_field, new_field, data) except Exception as e: pass return update_note I want to take it more efficiency,and can ues it in model.save and form.save -
How to add new user in admin page in django?
I am trying to add user in admin page in django. Whenever I register in my site form it adds itself but whenever I try to add it in admin page, it gave me the error message. NotImplementedError at /admin/auth/user/add/ UNKNOWN command not implemented for SQL SAVEPOINT "s6856_x1" C:\Users\Bilal\Envs\trial\lib\site-packages\djongo\sql2mongo\query.py in parse handler = self.FUNC_MAP[sm_type] -
Nested object dipslayed in main object django
I have problem with nested objects in Django. I would like not return to main response nested objects. Actually I have reponse: [ { "display_name": "Link1", "link": "http://facebook.com", "sub_links": [ { "display_name": "Link3", "link": "http://vk.com" }, { "display_name": "Link2", "link": "http://google.com" } ] }, { "display_name": "Link2", "link": "http://google.com", "sub_links": [] }, { "display_name": "Link3", "link": "http://vk.com", "sub_links": [] } ] and I would like receive: [ { "display_name": "Link1", "link": "http://facebook.com", "sub_links": [ { "display_name": "Link3", "link": "http://vk.com" }, { "display_name": "Link2", "link": "http://google.com" } ] } ] My viewset: class LinksViewSet(ReadOnlyModelViewSet): queryset = Links.objects.all() serializer_class = LinksSerializer permission_classes = (AllowAny, ) pagination_class = None My serializer: class SubLinksSerializer(serializers.ModelSerializer): class Meta: model = Links fields = ('display_name', 'link', ) class LinksSerializer(serializers.ModelSerializer): sub_links = SubLinksSerializer(many=True, read_only=True) class Meta: model = Links fields = ('display_name', 'link', 'sub_links') I really don't know how should I do it. What is more I tried find solution in documentation Django.