Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django Project show me UserInfo matching query does not exist
Here is views.py code. In the def index section, I use UserInfo model.Here information store in one to one relation so I write (user__pk=user_id) from django.shortcuts import render from Login_app.forms import UserForm, UserInfoForm from Login_app.models import UserInfo from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.contrib.auth.decorators import login_required from django.urls import reverse def index(request): dict={} if request.user.is_authenticated: current_user = request.user user_id = current_user.id user_basic_info = User.objects.get(pk=user_id) user_more_info = UserInfo.objects.get(user__pk=user_id) dict = {'user_basic_info':user_basic_info, 'user_more_info':user_more_info} return render(request, 'Login_app/index.html', context=dict) Here is models.py code.where I create UserInfo model.It store user,facebook_id,profile_pc. from django.db import models from django.contrib.auth.models import User # Create your models here. class UserInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) facebook_id = models.URLField(blank=True) profile_pic = models.ImageField(upload_to = 'profile_pics', blank=True) def __str__(self): return self.user.username -
Set iframe url to access pages in navigation bar in Django
I am new to Django framework. I am trying to use html pages in templates and get the interfaces. I got all of the pages one by one. Now I want them appear in an iframe. Here is my html code in homeAdmin.html page. <body> <div class="main-nav"> <div class="main-nav-ul"> <a href="{% url 'welcomeAdmin' %}" target="frame1"><span class="fa fa-home fa-lg"></span> Home</a> <a href="{% url 'register' %}" target="frame1"><span class="fa fa-user-plus fa-lg"></span> Register</a> <a href="{% url 'company' %}" target="frame1"><span class="fa fa-building fa-lg"></span> Company</a> <a href="{% url 'supplier' %}" target="frame1"><span class="fa fa-taxi fa-lg"></span> Supplier</a> <a href="{% url 'category' %}" target="frame1"><span class="fa fa-mouse-pointer fa-lg"></span> Category</a> <a href="{% url 'role' %}" target="frame1"><span class="fa fa-id-badge fa-lg"></span> Role</a> </div> <div class="target"> <iframe src="{% url 'welcomeAdmin' %}" name="frame1" id="frame1" style="width: 100%;height: 540px; float: right;"></iframe> </div> </div> </body> And here is the views.py code that I have written for this problem. ``` from django.shortcuts import render from django.http import HttpResponse def welcomeAdmin(request): return render(request, 'newapp/welcomeAdmin.html') def category(request): return render(request, 'newapp/category.html') def company(request): return render(request, 'newapp/company.html') def register(request): return render(request, 'newapp/register.html') def role(request): return render(request, 'newapp/role.html') def supplier(request): return render(request, 'newapp/supplier.html') def homeAdmin(request): return render(request, 'newapp/homeAdmin.html') ``` I am lack of knowledge about what to do next in which file, like in … -
Avoid different representation of the same serializer. Django Rest Framework
Imagine I have a model which looks like following: class Author(models.Model): book = models.ManyToManyField() and a serializer for Book objects: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('title',) def to_representation(self, obj): return obj.title I am using it to represent Book objects for Author entities. I have two different serializers for GET and POST requests but the books field is absolutely the same. class AuthorSerializer(serializers.ModelSerializer): books = BookSerializer(read_only=True, many=True) class Meta: model = Author fields = ('books', ...) My problem is that one AuthorSerializer (GET requests) returns data correctly: books = ['...', '...'] while the one for POST requests returns it with IDs. books = [{'id': 1, 'title': '...'}] What am I missing? Thanks. -
How to extend an array or append a value to array field on Django ORM's Queryset Update? [Postgresql]
I have an ArrayField to store Colors for a given Dish object in a Schema and the dishes also have a category class Dish(models.Model): colors = ArrayField(models.CharField(max_length=16)) category = models.CharField(max_length=32) Let's say I have 15 Dish objects, out of which 13 belong to the "Cookware" category and the remaining 2 belong to "Modware" Now I want to append a color to the existing list of colors for a given category in a single update query method (Which has to append my new color to all the array fields of matching Dishes, 13 items in my case) Following are the ways that I have tried to perform this operation and ended up having errors Dish.objects.filter(category="Cookware").update(colors=F("colors")+"red") Dish.objects.filter(category="Cookware").update(colors=F("colors")+["red"]) Following is the error message I am facing when I am trying with the above two queries No operator matches the given name and argument types. You might need to add explicit type casts The following obviously doesn't work as apppend will return None Dish.objects.filter(category="Cookware").update(colors=F("colors").append("red")) PS: Using Django(3.2), Django ORM, Postgres ArrayField from django.contrib.postgres.fields import ArrayField Thanks in advance for spending your time to help me solve this. -
How to I added load more button to show more comments in my django project template with jquery or ajax?
In my django template i don't want to list all comments.If user click show more button,load some more comments.I researched much but I don't know any jquery ,ajax or javascript knowledge.So I did't.Is there anyone who can help me? profile.html <div class="widget review-listing"> <ul class="comments-list" id="loadmorecomment"> {% if comments %} {% for comment in comments %} <li> <div class="comment"> <img class="avatar avatar-sm rounded-circle" alt="User Image" src="{{comment.comment_user.image.url}}"> <div class="comment-body"> <div class="meta-data"> <span style="white-space:pre" class="comment-author">{{comment.comment_user.unvan}} {{comment.comment_user.get_full_name}}</span> <span class="comment-date">{{ comment.updated_date|timesince }}</span> <div class="review-count rating"> {% if comment.star != 0 %} {% for i in comment.star|rjust:comment.star %} <i class="fas fa-star filled"></i> {% endfor %} {% endif %} {% if comment.none_star != 0 %} {% for i in comment.none_star|rjust:comment.none_star %} <i class="fas fa-star"></i> {% endfor %} {% endif %} </div> </div> <p class="comment-content"> {{comment.comment}} </p> </div> </div> </li> {% endfor %} {% else %} <p style="color: orange;">No comment</p> {% endif %} </ul> <!-- Show All --> <div class="all-feedback text-center"> <a id="#loadMore" name="more_comments" href="#" class="btn btn-primary btn-sm"> Load more comments <strong>({{comments.count}})</strong> </a> </div> <!-- /Show All --> </div> -
How to get all the fields from my model in Django
Here is my Model.py class BlogModel(models.Model): blog_id = models.AutoField(primary_key=True) title = models.CharField(max_length=1000) content = FroalaField() user = models.ForeignKey(User, blank=True , null=True , on_delete=models.CASCADE) image = models.ImageField(upload_to='public') created_at = models.DateTimeField(auto_now_add=True) upload_to = models.DateTimeField(auto_now=True) Here is my View.py def my_blogs(request): d = BlogModel.objects.all().filter(user = request.user) return render(request,"my_blogs.html",{'message' : d}) But when I try to get the blog_id and created_at fields then it will shows an error that the requested fields are not present in the respective table. But you can see that the field is n the table itself. Please help -
Data missing from plotly graph
I am trying to display some sensor data in a plotly-dash graph with django. I have noticed that in some scenarios, data is ommitted from the graph and only displayed properly once the timesale has been zoomed out (see below). I am currently using the following code: ambientTempApp = DjangoDash("ambientTemp") ambientTempApp.layout = html.Div([dcc.Graph(id='tempGraph'), dcc.Slider( id="tempSlider", marks={1: {'label': '1 Day'}, 7: {'label': '1 Week'}, 31: {'label': '1 Month'}, 62: {'label': '2 Months'}, 182: {'label': '6 Months'}, 365: {'label': '1 year'}}, max=365, min=1, value=7, step=1, updatemode='mouseup' ), html.P(className="description-text", id='ambientOutput')]) @ambientTempApp.callback([Output('tempGraph', 'figure'), Output('ambientOutput', 'children')], [Input('tempSlider', 'value')]) def update_figure(value): value *= 48 TIMESTAMPS = [datetime.datetime.fromtimestamp(x) for x in self.dataTimestamps[::-1][:value]] ambientTemp = self.dataAmbientTemp[::-1][:value] fig = Figure(data=Scatter(x=TIMESTAMPS, y=ambientTemp, mode="lines+markers", name="Ambient Temperature")) fig.update_layout(showlegend=False, transition_duration=250) return fig, f"Displaying data from {str(TIMESTAMPS[-1]).split('.')[0].replace('-', '/').replace(' ', '-')} to {str(TIMESTAMPS[0]).split('.')[0].replace('-', '/').replace(' ', '-')}" return None I suspect that the reason for this is that the graph is running out of space to display the points when they are varying less. Is there a variable I can set to ignore the lack of space and display the data anyway? Before zooming out, some data is omitted: And then it is displayed again: -
django, postgis app , cpu usage spikes to 100%
We have a location based django application using geodjango, running in docker / google cloud vm + sql instance ( vm: e2-medium (2 vCPUs, 4 GB memory), sql :1 vCPU,3.75 GB ). we basically have a search_listing_view which retrieve listing( 41k for now) from database based on user entered location( lat, lng) and max_dtaince in km Listing.objects.filter(location__distance_lte=(user_location, D(km=radius))), a simple request to this view is making the vm cpu usage spikes to nearly 100%, when db cpu never reach 20% usage. here is a screenshot of the top command when making a request to search_listings_view top command screenshot my question is: the heavy calculations related to distance operations are supposed to be handled by database cpu/instance not the vm , vm here is just querying the database , can this spike of cpu usage be related to nginx / gunicorn configuration, i also prifiled the gunicorn preccess with py-spy, prifile.svg: enter link description here py-spy top command py-spy dump -
Django create a database with model using django_auth_models Groups
ive a sqlite3 database with a table using Groups model from django_auth_models Groups is used as a field in one model When creating my database(makemigrations) , this does not work because python tries to create my model with the uncreated Group inside The only way to solve if that ive found is to comment lines using django_auth_models , to create the database , to uncomment then to create the database . Thanks -
Django object id is empty
I am a beginner at Django I have a URL like that ''' url(r'^(?P<question_id>[0-9]+)/$',views.details,name='details') ''' want to navigate to it through the Django template print question.id but questions.id is always empty ? how to write it correctly? -
How to integrate existing authentication system in website built using WIX?
I am exploring WIX to build a website. I have my existing login/signup (authentication system) build using Django + Python. I would like to use it in WIX instead of their own login/signup. I tried to find the solutions on Google but did not find anything promising. Any links for guiding on this will be really appreciated. -
Django many to many with two models?
I have two models Students, University. By using this, student can apply for a course in university and the requirements is when a student apply for a course in university, i need to create a application ( planning to create separate model for application ) And this application can been accessed by both student & university. The purpose of making both access the application is because there are many post apply data's to be manipulated later ! So how to create a common application table - so both can access or its not effecient to create a seprate table ? Please guide on how to tackle this ! Option1: Can a many to many be combined with Student and University to create a application model Option2: Add manytomany field to students model itself with University as foreign key ? I have records about more than 1 million so am bit concerned about efficiency ! Which is better option to handle two way communication -
Deleting objects once used
I am building a simple web app, in which - I am trying to implement a feature that - If a word inputted by user in the Another models's objects then the word will be deleted, I mean, I have stored few names on a model like :- car, bike, rain, and calendar. And I made another model named BlogPost, So when user submit form and if the mentioned name in the another model's objects then the name will be deleted. but the name is not deleting. models.py class BlogPost(models.Model): title = models.CharField(max_length=30,default='') name = models.CharField(max_length=30,default='') class All_Name(models.Model): names = models.CharField(max_length=30,default='') User will submit his/her name, And I will store existing Names in model All_Name , And if typed name in model All_Name than name will delete. views.py def new_blog_post(request): allNames= All_Name.objects.all().values_list('names', flat=True) if request.method == 'POST': form = PostForm(data=request.POST) if form.is_valid(): formName = form.cleaned_data['name'] new_post = form.save(commit=False) if formName in allNames: new_post.save() # Deleting Here allNames = formName allNames.delete() else: return redirect('home') else: form = PostForm() context = {'form':form} return render(request, 'new_blog_post.html', context) What have i tried ? :- I have also tried :- formName.delete() But it is not saving anything and not deleting the Name. Then i tried … -
How to return custom response for successful password, using values from the request object, in django-rest-registration?
I am trying to return a custom response for reset-password using, django-rest-registration. I have tried, using the SUCCESS_RESPONSE_BUILDER settings to override the method, but the method doesn't have the request, or the request data. Is there a way to override the response -
How to use Django Formset in Formwizard
I have created a from wizard with 3 steps forms, on this second step I have a using a Formset which is dynamically updating. I am able to get the step1 & step2 data in the form list done() method but Formset data is not getting. -
Don't work button 'Send' for django private chat
I installed the django private chat package, but the send button does not work. I configured everything properly settings.py CHAT_WS_SERVER_HOST = 'localhost' CHAT_WS_SERVER_PORT = 5002 CHAT_WS_SERVER_PROTOCOL = 'ws' template/base.html {% block css %}{% endblock css %} {% block content %}{% endblock content %} {% block extra_js %}{% endblock extra_js %} in the dialogs.html files I have the exact code from the package. -
Mongoengine - __init__() missing 1 required positional argument: 'parent_document'
Unfortunately the documentations of mongoforms and mongoadmin are unavailable (some chinese scam sites appears when I'm trying to enter) and I cant't get an answer. Every time when I'm trying to create a new instance of ManHourtsTarget the django admin raises above error. class ShiftDocument(EmbeddedDocument): monday = mongoengine.IntField() class ManHoursTarget(Document): week = mongoengine.StringField(unique=True, required=True, choices=generate_weeks_choices()) shifts = mongoengine.EmbeddedDocumentListField(ShiftDocument) -
Unable to bind Django application with Gunicorn
It has been very difficult for me trying to deploy to aws EC2 ubuntu server SINCE I'm coming from windows background. I encounter an error while trying to bind django application to gunicorn. The command I'm running is sudo gunicorn --bind 0.0.0.0:8000 logistics.wsgi:application And the error log is show below: (venv) ubuntu@ip-172-31-18-196:/var/www/html$ sudo gunicorn --bind 0.0.0.0:8000 logistics.wsgi:application [2021-09-08 11:21:00 +0000] [29379] [INFO] Starting gunicorn 20.1.0 [2021-09-08 11:21:00 +0000] [29379] [INFO] Listening at: http://0.0.0.0:8000 (29379) [2021-09-08 11:21:00 +0000] [29379] [INFO] Using worker: sync [2021-09-08 11:21:00 +0000] [29382] [INFO] Booting worker with pid: 29382 [2021-09-08 11:21:00 +0000] [29382] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/usr/local/lib/python3.5/dist-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/usr/local/lib/python3.5/dist-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.5/dist-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in … -
Django Views: Accessing multiple single objects from a single ListView Class (and not DetailView)
The code that I have currently but not working is this views.py class HomeView(ListView): model = Blog template_name = 'main/homepage.html' def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context['featureone'] = Blog.objects.order_by('publishDate').reverse()[0] context['featuretwo'] = Blog.objects.order_by('publishDate').reverse()[1] return context homepage.html <div> <a href="{% url 'main:home' featureone.id %}"> <h4>{{ featureone.title }}</h2> <p>{{ featureone.extract }}</p> </a> </div> <hr style="border-top: 0.7px solid black; margin: 7%;"> <div> <a href="{% url 'main:home' featuretwo.id %}"> <img src="{{ featuretwo.featureImage.url }}" alt="{{ featuretwo.title }}"> <h2>{{ featuretwo.title }}</h2> <p>{{ featuretwo.extract }}</p> </a> </div> Anyone with a solution or an alternative way (without using DetailView)? -
How to update a modelfield based on another model in Django?
I have two models in Django. One for the products and another is for ratings. Product Model: class Product(models.Model): ... product_name = models.CharField(max_length=264, blank=False, verbose_name='Product Name') product_slug = models.SlugField(blank=True) avg_rating = models.IntegerField(blank=True, null=True, verbose_name='Average Rating', help_text='Do not Edit!') total_rating_count = models.IntegerField(blank=True, null=True, verbose_name='Total Rating', help_text='Do not Edit!') def save(self, *args, **kwargs): ... super(Product, self).save(*args, **kwargs) def __str__(self): return self.product_name Rating Model: class Rating(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_ratings') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_rating') product_rating = models.IntegerField(verbose_name='Rating', blank=False) product_comment = models.TextField(verbose_name='Comment', blank=False) What I want to do is that when a user rates a product, I want to update the avg_rating and total_rating_count in the Product model. How can I do that? Thank you. -
Django python stack overflow somewhere in template
I have a django app and I have made some changes to the tempate inheritance. I am getting stack overflow i dont know where from. Sometimes the page loads but while running im getting this error. Sometimes the error is throwed when server starts. The block renders a dashboard which is inside dashboard.html wrapped in a content block. base.html <!DOCTYPE html> <html> <head> // stuff </head> <body> {% block content %} {% endblock content %} </body> </html> ystem check identified no issues (0 silenced). September 08, 2021 - 12:54:38 Django version 3.1.3, using settings 'auth.settings.development' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Fatal Python error: _Py_CheckRecursiveCall: Cannot recover from stack overflow. Python runtime state: initialized Thread 0x00002910 (most recent call first): File "C:\Users\bratca\AppData\Local\Programs\Python\Python39\lib\socket.py", line 704 in readinto File "C:\Users\bratca\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\servers\basehttp.py", line 182 in handle_one_request File "C:\Users\bratca\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\servers\basehttp.py", line 172 in handle File "C:\Users\bratca\AppData\Local\Programs\Python\Python39\lib\socketserver.py", line 720 in __init__ File "C:\Users\bratca\AppData\Local\Programs\Python\Python39\lib\socketserver.py", line 360 in finish_request File "C:\Users\bratca\AppData\Local\Programs\Python\Python39\lib\socketserver.py", line 650 in process_request_thread File "C:\Users\bratca\AppData\Local\Programs\Python\Python39\lib\threading.py", line 888 in run File "C:\Users\bratca\AppData\Local\Programs\Python\Python39\lib\threading.py", line 950 in _bootstrap_inner File "C:\Users\bratca\AppData\Local\Programs\Python\Python39\lib\threading.py", line 908 in _bootstrap Current thread 0x00000fe4 (most recent call first): File "C:\Users\bratca\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 220 in wrapper File "C:\Users\bratca\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 782 in __init__ File "C:\Users\bratca\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line … -
Firefox loading sprite images but other browsers don't
I am making a web game in Django which uses a realtime Websocket connection with python script. I added sprite images in my game. Firefox is loading images fine but other browsers (chrome, brave, edge) are loading when the websocket connection closes. I doubt if Firefox works different in loading images (like preloading them). Any ideas how can I achieve same in other browsers? Please tell if I need to provide any mode details. -
Value of hidden field undefined when submitted after creation using javascript
I'm using django and trying to get javascript to add a hidden field and then pass to a view try to process the value. When I hard code the hidden field using the following in my template: <form action="{% url 'add_hamper' hamper_id=hamper.slug %}" method="post" novalidate id="form"> {% csrf_token %} <input type="hidden" name="option_id" id="option_element" value="85"> <button type="submit" class="btn btn-sm btn-success" id="price_button" data-price="{{ hamper.sale_price }}">{{ hamper.sale_price }}</button> </form> Everything works and I can see the value of the option_id in my view: <QueryDict: {'csrfmiddlewaretoken': ['XXXX'], 'option_id': ['85']}> However, when I start with the following HTML: <form action="{% url 'add_hamper' hamper_id=hamper.slug %}" method="post" novalidate id="form"> {% csrf_token %} <button type="submit" class="btn btn-sm btn-success" id="price_button" data-price="{{ hamper.sale_price }}">{{ hamper.sale_price }}</button> </form> And then use the following javascript to add the hidden field. I know it's ugly at the moment and I could probably do it in a more concise way, but I'm still trying to learn the best ways. let form = document.getElementById('form'); let option_element = document.getElementById('option_element'); if (option_element){ option_element.remove(); } let input_elem = document.createElement("input"); input_elem.setAttribute("type", "hidden"); input_elem.setAttribute("name", "option_id"); input_elem.setAttribute("id", "option_element"); input_elem.setAttribute("value", option_id); form.prepend(input_elem); Whilst the console is showing this (which appears to be exactly the same: <form action="/hampers/add_hamper/premium-nibbles" method="post" novalidate="" id="form"> <input type="hidden" … -
understand a view script in Django
hi guys i'm starting to see django in particular how the views are structured. I have some unresolved doubts as an amateur. . Here, for example, I have a view that should show all the products in the database on a page. class HomeView(EcomMixin, TemplateView): template_name = "home.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) all_products = Product.objects.all().order_by("-id") paginator = Paginator(all_products, 8) page_number = self.request.GET.get('page') print(page_number) product_list = paginator.get_page(page_number) context['product_list'] = product_list return context "get_context" returns a dictionary representing the context of the model, but I don't understand what "self and kwargs" would be. Then extra elements are added to the model with the call "super().Get_context_data(** kwargs)." Then all the products present are taken and ordered "all_products = Product.objects.all(). Order_by("-id") ". Here I don't understand that "order_by("-id")" . In the" Product "table there is no field named id. Paginator comes with a list of objects as well as the number of elements you want to have on each page. Then the page number is requested with the get method and printed. (Why is it printed?) "product_list = paginator.get_page(page_number)", returns a specific product page in product_list. I don't understand what is done in the penultimate line. -
How to serialize nested generic relations in django rest frame work
there is a little bit complex model in the project. There are three models bind to each other by generic relations. Here is the example models: class Person(models.Model): first_name = models.CharField() last_name = models.CharField() ptype = models.CharField() mapping = models.ForeignKey("Mapping", related_name="mapping") class Profile(models.Model): rank = models.CharField() company = models.ForeingKey("Company") class Company(models.Model: name = models.Charfield() class Mapping(models.Model): origin_person_ctype = models.ForeignKey(ContentType, related_name="origin_mapping") origin_person_id = models.PositiveIntegerField() origin_person_object = GenericForeignKey('origin_person_ctype', 'origin_person_id') mapped_profile_ctype = models.ForeignKey(ContentType, related_name="mapped_mapping") mapped_profile_id = models.PositiveIntegerField() mapped_profile_object = GenericForeignKey('mapped_profile_ctype', 'mapped_profile_id') company = models.ForeignKey("Company") And there is a Rest API for getting data from Person model. class PersonAPIView(generics.RetrieveUpdateAPIView): serializer_class = PersonSerializer lookup_url_kwarg = 'person_id' def get_queryset(self): return Person.objects.all().prefetch_related( "mapping", "mapping__mapped_profile_object", "mapping__company" ) class PersonSerializer(serializers.ModelSerializer) class Meta: model = Person fields = ( 'id', 'first_name', 'last_name', 'type', ) Now, I have to add Company.name and Profile.rank as nested dictionary list in PersonSerializer class. How can I serialize that generic relation values like this: [ {"company1": "rank1"}, {"company2": "rank2"} etc... ]