Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
During TestCase execution django.db.connection.cursor() SQL query returning data from main DB, not from the test one
Dears, I'm facing a problem which I have no more ideas how to resolve. I have need to test data which is returned by direct query from database. During execution of TestCase django.db.connection.cursor() is returning data from main database, not from test one, which contain fixtures prepared for this test purposes. I've tried to use both TestCase and TransactionalTestCase. I've tried debugging, checking variables values and found out that connection is pointed onto test database for sure. Do you know why it's returning data from main database? Is there any case when Django is copying data from main database to this created for tests purposes? I'm using: Python 3.6.5, Django 2.1, pytest 4.6.3, pytest-django 3.5 Thanks in advance for any support. -
How may seconds may an API call take until I need to worry?
I have to ask a more or less non-typical SO question and hope you don't mind. Right now I am developing my very first web application. I did set up an AJAX function that requests some data from a third party API and populates my html containers with the returned data. Right now I query one single object and populate 3 html containers with around 15 lines of Javascript code. When i activate the process/function by clicking a button on my frontend, it needs around 6-7 seconds until the html content is updated. Is this a reasonable time? The user experience honestly will be more than bad considering that I will have to query and manipulate far more data (I build a one-site dashboard related to soccer data). There might be very controversal answers to that question, but what would be a fair enough time for the process to run using standard infrastructure? 1-2 seconds? (I will deploy the app on heroku or digitalocean and will implement a proper caching environment to handle "regular visitors"). Right now I use a virtualenv and django server for the development and a demo server from the third party API which might be slowed … -
Problems with nginx+gunicorn resolving static content
I am setting up an environment with a django application (askbot opensource project), gunicorn and nginx. With nginx and gunicorn in different docker containers. This is my nginx configuration. server { listen 80; location /static { alias /askbot/static; } location /m { alias /askbot/static; } location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://askbot:8080/; } } If I run the django app on debug mode, everything is ok, I can go through nginx and I see how nginx is only invoking gunicorn for the dynamic content, and the static content is resolved locally. But, when I run the django application with debug false, nginx does not revolve the static content, and if I see the source code for the web page, I can see all the paths for the static content have changed, using somethign like "/m/CACHE...". I guess this is the reason why nginx cannot resolve the static content anymore. For example, when using debug mode equals false, this is one fragment of the html source code. <link rel="stylesheet" href="/m/CACHE/css/9275d0e5b87f.css" type="text/css" /> <link href="//fonts.googleapis.com/css?family=Open+Sans+Condensed:700&amp;subset=latin-ext" rel="stylesheet" type="text/css" /> <link href="//fonts.googleapis.com/css?family=Open+Sans+Condensed:700&amp;subset=cyrillic-ext" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="/m/default/media/jslib/modernizr.custom.js?v=1"></script> <script type="text/javascript"> And when running with debug equals false, … -
Backend in a hosting using Django and cpanel
I need help with my project, I am working on an application using Django as a backend and Angular as a fronted, I would like to know how to upload my Django backend to the hosting cpanel using MYSQL or PostgreSql. Or do I have to upload the full backend, or can I only upload the database? Thank you -
django rest framework offline documentation
I need to get the documentation for django rest framework for offline usage, Why? b/c I live in Ethiopia and the internet is too damn slow for me to go online just to the doc of APIView. So does anybody know of a link where I can find the offline version of the documentation? The pdf on readthedoc is outdated and empty and I can't seem to find any other alternative. Can anyone help? -
Django filter with manytomanyfield
This is my models class Person(models.Model): name = models.CharField(max_length=50) is_group_member = models.BooleanField(default=False) class Group(models.Model): members = models.ManyToManyField(Person) @receiver(post_save, sender=Group) def set_group_member_type(sender, instance, created, **kwargs): if created: # change the all group members' type I am trying to update is_group_member field with signal. When a group is created with members, then i will filter and retrieve all the person who are group member, then i will change the is_group_member value to True Can anyone help me to achieve this? -
Get response empty fields error after passing form to django rest api
I'm trying to build passing formdata to api page. But, the response is empty fields error. This is my vue template. <b-form @submit.prevent="postImitagram" id="post-form"> <b-form-input id="words" v-model="content" :state="state" trim /> <b-form-file accept="image/*" id="image" v-model="file" :state="Boolean(file)" /> <b-button block class="mt-5" type="submit" variant="primary">submit </b-button> </b-form> data() { return { content: "", file: null, error: '' } }, methods: { postImitagram(e) { let endpoint = "/api/posts/"; let method = "POST"; let formData = new FormData(); formData.append('title', this.content); formData.append('image', this.test, this.test.name); let context = {'title': this.content, 'image': this.file}; apiService(endpoint, method, formData).then(data => { }) } } function apiService(endpoint, method, data) { const config = { method: method || "GET" body: data, headers: { 'content-type': 'multipart/form-data', 'X-CSRFTOKEN': CSRF_TOKEN } }; return fetch(endpoint, config) .then(handleResponse) .catch(error => console.log(error)) } api model { "title": "", "image": null } and response status 400 bad request and 'title' and 'image' field are required. Creating a new one works fine when i post things in api page itself. What did I miss? Thank you in advance -
Django API Chart.js
Im would like to change the Chart Type from Bar Chart to Line Chart with an ajax call. For a start I saved the Chart Types (Bar, Line, Scatter) in a Model as follows: class Chart(models.Model): ctype = models.CharField(max_length=20, choices=choices, default='bar') choices = ( ('line', 'line'), ('bar', 'bar'), ('radar', 'radar'), ('bubble', 'bubble'), ('scatter', 'scatter'), ) and I pass them to view, serialising them and passing them on class ChartData(APIView): def get(self,request,format=None): dataset = Mobiles.objects.all() serializer = TypeSerializer(dataset,many=True) ctype = serializer.data data = { "ctype":[item["ctype"] for item in ctype], } return Response(data) to the api which returns: "ctype": [ "bar", "bar", "bar", ] And finally I retrieve them from the api, and set them equal to the chart type. var endpoint = '/api/chart/data/' var price = [] var labels = [] var ctype = [] $.ajax({ method: 'GET', url: endpoint, success: function(data){ labels = data.labels price = data.price ctype = data.ctype setChart() }, error:function(error_data){ console.log("error") console.log(error_data) } }) function setChart(){ var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: ctype, data: { labels: labels, datasets: [{ label: '#', data: price, }] } }) } But the chart does not work Thank you for any help -
Implementing one to many between an article and page models in Wagtail
I'm trying to setup a wagtail site with an article to pages structure but I'm struggling. A review article for example may have an introduction page, a benchmark page and a conclusion page. I want to work out how to allow this relationship in wagtail and have it so that editors can add multiple pages to the same article on the same page. I can imagine the pages interface looking a bit like how you have content, promote and settings on pages but with the ability to add, rename and reorder pages. I've tried using a foreign key on a page model that links to an article but I can't get it to be shown in the admin the way I want. -
How do i count objects that has an id below the current id in django
class Shoe(models.Model): title = models.Charfield(max_length=120) the querry, i am using is old_shoes = Shoe.objects.all().count() i want to get shoes with id's below the current id, would something like this work old_shoes = Shoe.objects.all(id>shoe.id).count() -
Collectstatic is giving NoSuchKey while using s3boto3 and manifestfilemixin
class NSStaticStorage(ManifestFilesMixin, S3Boto3Storage): pass NoSuchKey: An error occurred (NoSuchKey) when calling the ListObjects operation: The specified key does not exist. I am getting this error while integrating s3boto and manifest for cache busting -
Django push notification, editing the content dynamically
I have a function which register a new user then i wanna send a email with a message, i know how to do that writing a message into code, but i want some way to make it more dynamic editing this message in admin or any page but not in code, just like "Notification – Custom Notifications and Alerts for WordPress" does. Basically when i edit this message in admin or other page the content which fuction send is changes as well. -
Django Pagination - re group and show group of times per page?
Im currently regrouping some data and then displaying that data in columns whilst also using pagination. However, due to the ordering of the origin data, there are instances where column 1 has 1 entry in but actually has 5 or 6 total entries, but they would be on different pages, is it possible to regroup the data so that the number of items per page is taken by the number of grouped items? I thought about sorting the data before posting it to the page but then that will only show the one column of types per page (there could be 1 or n types/columns that id like to have on one page) note: the sample data below is not actual data, The below example hopefully will make things clearer orgin data: ID Type Item ---------------------------- 9 Fruit Apple 15 Meat Beef 18 Fruit Lemon 99 Fruit Orange 9 Fruit Grape 77 Meat Chicken Paginated and grouped data current output Meat Fruit ------- ------- Beef Apple Lemon page 1 of 2 (3 items per page) Meat Fruit ------- ------- Chicken Orange Grape page 2 of 2 (3 items per page) Desired Output Meat Fruit ------- ------- Beef Apple Chicken Lemon … -
Django Include external library without CDN
I have a Django project (git but not public yet) and I want to include a Javascript library that does not provide a CDN url. It should: Not be inside the Django project (eg. 'static' dir) Be pypi compatible What is the proper way to include this into my project? -
GCP App Engine deploy - Failed to build logilab-astng
I'm posting this to hopefully help anyone else with the same problem. I've used the GCP documentation to deploy my python application to GCP App Engine. I was getting the following failure with log out of: ERROR: build step 1 "gcr.io/gae-runtimes/python37_app_builder:python37_20190907_3_7_4_RC00" failed: exit status 1 ERROR Finished Step #1 - "builder" Step #1 - "builder": IOError: [Errno 2] No such file or directory: '""/output' Step #1 - "builder": File "/usr/local/bin/ftl.par/__main__/ftl/common/ftl_error.py", line 58, in UserErrorHandler Step #1 - "builder": File "/usr/local/bin/ftl.par/__main__.py", line 57, in main Step #1 - "builder": File "/usr/local/bin/ftl.par/__main__.py", line 65, in <module> Step #1 - "builder": exec code in run_globals Step #1 - "builder": File "/usr/lib/python2.7/runpy.py", line 72, in _run_code Step #1 - "builder": "__main__", fname, loader, pkg_name) Step #1 - "builder": File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main Step #1 - "builder": Traceback (most recent call last): Step #1 - "builder": error: `pip_download_wheels` returned code: 1 Step #1 - "builder": Step #1 - "builder": ERROR: Failed to build one or more wheels Step #1 - "builder": Failed building wheel for logilab-astng Step #1 - "builder": ERROR `pip_download_wheels` had stderr output: Step #1 - "builder": INFO full build took 24 seconds Step #1 - "builder": INFO build process for … -
How can create model that couldn't be changed by admin?
I need to create Django model that couldn't by admin, but he should be avialable to see it. It's content will be input from site. How can I do it? -
Serving Django and Vue with Nginx
I have a website which uses Django for the API and Vue for the frontend. Currently when I deploy the site I do the following: Create a production build of the Vue app (npm run build) Copy the Vue dist folder into a specific folder within the Django app One of the Django urls is setup as a TemplateView which serves up the Vue index.html By doing the above, Nginx in production simply serves up the Django app using gunicorn and everything works. However I would prefer to have Nginx serve up the Vue index.html and static files. This would allow me to create the Vue production build without any need for any changes on the Django side. Here is my current Nginx config: upstream appserver_wsgi_app { server localhost:8000 fail_timeout=0; } server { listen 80; server_name www.example.com; rewrite ^(.*) https://$server_name$1 permanent; } server { server_name www.example.com; listen 443 ssl; ... ... ... location /static { autoindex on; alias /home/user/static_django_files/; } location /media { autoindex on; alias /home/user/media_django_files/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request-filename) { proxy_pass http://appserver_wsgi_app; break; } } } What needs to be changed in Nginx? Also, does anything need … -
Django filter returning empty query set even though there is a match to data
I have a Django site, and am looking to filter my model for a specific field. The field, CreatedDate is a datetime field, and it is returning none, even though I am certain that the data I specify is in the query set. I have tried casting the user entered date to a datetime object, parsing through the query set and adding each models CreatedDate into a list, and then checking if the user entered date is in the list, which it is( this is how I know the data is there views.py if createdDate[0] == '>': createdDate = createdDate[1:] cd = datetime.strptime(createdDate, '%Y-%m-%d') try: query_results = query_results.filter(CreatedDate__gte=cd) except Exception as e: print2(e) elif createdDate[0] == '<': createdDate = createdDate[1:] cd = datetime.strptime(createdDate, '%Y-%m-%d') try: query_results = query_results.filter(CreatedDate__lte=cd) except Exception as e: print2(e) else: cd = datetime.strptime(createdDate, '%Y-%m-%d') try: print2(createdDate) print2(query_results) query_results = query_results.filter (CreatedDate__icontains=cd) except Exception as e: print2(e) models.py CreatedDate = models.DateTimeField(blank=True, null=True) Database - Column CreatedDate sample 2019-08-09 10:33:06.700 2019-08-09 10:33:06.700 2019-08-09 10:33:06.700 2019-09-27 00:00:00.000 2019-09-27 00:00:00.000 2019-09-27 00:00:00.000 I have no Idea why the filter is returning an empty query set, even though the dates that I enter are clearly in the database. If I am … -
jQuery validate with many select multiple fields (with Django)
My form has automatically generated multiselect fields. This means I don't know how many of them will be created (depends on input file). Also, select name cannot be used since its autogenerated in a specific way, so I guess in jQuery I'd have to go with either class or ID. I've already tried few options I found on stackoverflow etc, and the best of what I could get to was my code below. It actually validates if there is at least one option selected, but across all of presented multiselect fields. So if I have 10 fields, in one of them one was selected, thats enough for submit button to work, which is not what I want. Theres the jQuery part: <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script> <script> $(function () { $('#myForm').submit(function () { var isValid = true; var form = this; isValid = isValid && validateMultipleSelect($('select.required', form)); return isValid; }); }); function validateMultipleSelect(select) { var number = $('option:selected', select).size(); alert("Select at least one option in each column per Vendor") return (number > 0); } Now this is the Form part: <form action="{% url 'index' %}" method="post" id="myForm"> {% csrf_token %} <p></p> <hr> {% for vendor in vendor_list %} {{ vendor.vendor_name }} … -
Error running WSGI application, ModuleNotFoundError: No module named 'django_countries'
I'm trying to deploy my webApp on PythonAnywhere but the following error occour: 2019-10-01 18:20:12,820: Error running WSGI application 2019-10-01 18:20:12,928: ModuleNotFoundError: No module named 'django_countries' 2019-10-01 18:20:12,928: File "/var/www/namesurname_pythonanywhere_com_wsgi.py", line 33, in <module> 2019-10-01 18:20:12,929: application = get_wsgi_application() 2019-10-01 18:20:12,929: 2019-10-01 18:20:12,929: File "/home/namesurname/.virtualenvs/myenv/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2019-10-01 18:20:12,929: django.setup(set_prefix=False) 2019-10-01 18:20:12,929: 2019-10-01 18:20:12,929: File "/home/namesurname/.virtualenvs/myenv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup 2019-10-01 18:20:12,929: apps.populate(settings.INSTALLED_APPS) 2019-10-01 18:20:12,930: 2019-10-01 18:20:12,930: File "/home/namesurname/.virtualenvs/myenv/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate 2019-10-01 18:20:12,930: app_config = AppConfig.create(entry) 2019-10-01 18:20:12,930: 2019-10-01 18:20:12,930: File "/home/namesurname/.virtualenvs/myenv/lib/python3.7/site-packages/django/apps/config.py", line 90, in create 2019-10-01 18:20:12,930: module = import_module(entry) Django_countries is successfully already installed, I used the bash console of python anywhere. I also installed other third party modules, like django-allauth, but no error about those. Since I have no idea where to look, instead of posting a bunch of probably non-related codes I'll post on request. This is my first webapp I'm trying to deploy, so any help or hint is really appreciated, thanks. -
Following Django official tutorial part 2, makemigrations issue, not getting Add field question to choice
I got stuck on part 2 of the Django official tutorial while trying to makemigrations after editing models.py. https://docs.djangoproject.com/en/2.2/intro/tutorial02/#activating-models I got only these two lines: /mysite$ python manage.py makemigrations polls Migrations for 'polls': polls/migrations/0001_initial.py - Create model Question - Create model Choice Missing "- Add field question to choice" which later results in issues while I'm trying to add choices in Python shell. I have been copying most of the code, nevertheless my models.py is currently back to: from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) Is there anything I could do wrong there to not get this "- Add field question to choice" ? Later when I was trying to add the first choice to that question console told me that: >>> q = Question.objects.get(pk=1) >>> q <Question: What's up?> >>> q.choice_set.all() <QuerySet []> >>> q.choice_set.create(choice_text='Not much', votes=0) Traceback (most recent call last): File "/usr/lib/python3.6/code.py", line 91, in runcode exec(code, self.locals) File "<console>", line 1, in <module> File "/home/rufus/.local/lib/python3.6/site- packages/django/db/models/base.py", line 519, in __repr__ return '<%s: %s>' % (self.__class__.__name__, self) File "/home/rufus/mysite/polls/models.py", line 19, in __str__ return self.question_text AttributeError: 'Choice' object has … -
IntegrityError at /add_contact/ NOT NULL constraint failed: contacts_contactcustomfield.custom_field_id
i my trying to submit my form but this error coming. i think my form data is not saved to the correct path.oiuodsijddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd views.py - my view file def addContact(request): if (request.GET): contact = Contact() contact.fname = request.GET['fname'] contact.lname = request.GET['lname'] contact.email = request.GET['email'] contact.mobile = request.GET['mobile'] contact.address = request.GET['address'] contact.pincode = request.GET['pincode'] contact.save() # contact.attribute.add(obj) for obj in Field.objects.all(): #contact.attribute.add(obj) custom_field = ContactCustomField() custom_field.contact = contact custom_field.custom_field = obj custom_field.custom_field_value = request.GET[obj.field_name] custom_field.save() print(request.GET[obj.field_name]) for obj2 in picklist.objects.all(): # contact.attribute.add(obj2) custom_field_picklist = ContactCustomField() custom_field_picklist.contact = contact custom_field_picklist.custom_field_picklist = obj2 custom_field_picklist.custom_field_value = request.GET[obj2.fieldname] custom_field_picklist.save() print(request.GET[obj2.fieldname]) messages.success(request, 'Contact Added Successfully') return redirect('add_contact') return render(request, 'add_contact.html', {'fields': Field.objects, 'fields2': picklist.objects}) mdoels.py- my model file my field model class Field(models.Model): field_name = models.CharField(max_length=100, unique=True) field_type = models.CharField(max_length=50) max_length = models.IntegerField(default=None) is_required = models.BooleanField() def __str__(self): return self.field_name class picklist(models.Model): fieldname = models.CharField(max_length=100, unique=True) isrequired = models.BooleanField() def __str__(self): return self.fieldname my contact model class Contact(models.Model): fname = models.CharField(max_length=200, null=True) lname = models.CharField(max_length=200, null=True) email = models.EmailField() mobile = models.IntegerField(max_length=10) address = models.CharField(max_length=200,default=None) pincode = models.IntegerField() created_date = models.DateField(auto_now=True) def name(self): return self.fname+" "+self.lname customfield model- class ContactCustomField(models.Model): custom_field = models.ForeignKey(Field, on_delete=models.CASCADE) custom_field_picklist = models.ForeignKey(picklist, on_delete=models.CASCADE) contact = models.ForeignKey(Contact, related_name='custom_data', on_delete=models.CASCADE) custom_field_value = models.TextField() … -
Error when trying to display a video in django
I'm trying to make a video display randomly on my homepage. A user is able to upload a video and it would be saved to a document in media/documents as well as to a dataset. I tried the code below and it keeps giving me an error, Exception Type: TemplateSyntaxError at / Exception Value: 'media' is not a registered tag library. Must be one of: admin_list admin_modify admin_static admin_urls cache i18n l10n log static staticfiles tz I removed if settings.DEBUG: from urls.py and added .url to {% media 'doc.document.url' %}, however this didn't work. home.html {% load media %} {% for doc in document %} <video width='320' height= '240' controls> <source src="{% media 'doc.document.url' %}" type='video/mp4'> Your browser does not support the video tag. </video> {% endfor %} models.py from django.db import models from datetime import datetime from django.contrib.auth.models import User from django.conf import settings ... class Document(models.Model): title = models.CharField(max_length=100, default='NoTitle') description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField("date published")#(auto_now_add=True) creator = models.ForeignKey('auth.User', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.title urls.py urlpatterns = [ path('admin/', admin.site.urls), path("", views.homepage, name="homepage"), path("myconta/", views.myconta, name="myconta"), path("upload/", views.model_form_upload, name="upload"), path("register/", views.register, name="register"), path('', include("django.contrib.auth.urls")), ] #if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) … -
How to create a grouped QuerySet for use in ModelAdmin.get_queryset
I want to be able to display a list of banned ip addresses grouped by ip, sorted descending by count and the latest time of ban, as an admin changelist. fail2ban generates a sqlite-db and debian-8/fail2ban-debian-0.9.6 generates this table: "CREATE TABLE bans(" \ "jail TEXT NOT NULL, " \ "ip TEXT, " \ "timeofban INTEGER NOT NULL, " \ "data JSON, " \ "FOREIGN KEY(jail) REFERENCES jails(name) " \ ");" \ "CREATE INDEX bans_jail_timeofban_ip ON bans(jail, timeofban);" \ "CREATE INDEX bans_jail_ip ON bans(jail, ip);" \ "CREATE INDEX bans_ip ON bans(ip);" the SQL i would like django to produce should return the same results as this SQL: SELECT ip, strftime('%Y-%m-%d %H:%M:%S', timeofban, 'unixepoch', 'localtime') as latest, COUNT(ip) as ipcount FROM bans GROUP BY ip ORDER BY ipcount DESC, timeofban DESC So i started to set up the additional db in settings: DATABASES = { ... 'fail2ban': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/var/lib/fail2ban/fail2ban.sqlite3', } } DATABASE_ROUTERS = [ 'fail2ban.dbrouter.Fail2BanRouter' ] Created a model: from django.db import models class Ban(models.Model): jail = models.CharField('jail', max_length=250) ip = models.CharField('ip', max_length=100) timeofban = models.IntegerField('timeofban', primary_key=True) data = models.TextField('data', blank=True, null=True) class Meta: db_table = 'bans' ordering = ["-timeofban"] managed = False def save(self, **kwargs): raise NotImplementedError() Setup … -
How to join three tables through nested Serialization
I have to join 3 tables through nested serialization, 2 tables have their foreign key relation in a third table. these are the tables, class Product_Sales(models.Model): product_key = models.ForeignKey('Product',on_delete= models.CASCADE, null=True,related_name='productkey') channel_key = models.ForeignKey('Channel', on_delete= models.CASCADE, null=True,related_name='channelkey') outlet_key = models.ForeignKey('Outlet',on_delete= models.CASCADE, null=True,related_name='outletkey') sales_type = models.TextField(null=True) date = models.DateField(null=True) sales_units = models.IntegerField(null=True) sales_volume = models.IntegerField(null=True) sales_amt = models.DecimalField(null=True,max_digits=8, decimal_places=3) sales_to = models.TextField(null=True) sales_from = models.TextField(null=True) objects = models.Manager() objects=CopyManager() class Outlet(models.Model): outlet_key = models.AutoField(primary_key=True) outlet_group = models.TextField(null=True) outlet_company = models.TextField(null=True) outlet = models.TextField(null=True) objects = models.Manager() objects=CopyManager() class Channel(models.Model): channel_key = models.AutoField(primary_key=True) channel = models.TextField(null=True) objects=CopyManager() serializer.py class ModelMappingSerializer(WritableNestedModelSerializer): outletkey=OutletSerializer(many=True,read_only=True) channelkey=ChannelSerializer(many=True,read_only=True) class Meta: model = Product_Sales fields = ['product_key','channel_key','outlet_key','sales_type','date','sales_units','sales_volume','sales_amt','sales_from','sales_to','sales_from','outletkey','channelkey'] Output on Postman [{ "product_key": 1, "channel_key": 1, "outlet_key": 1, "sales_type": null, "date": "2019-09-05", "sales_units": 22, "sales_volume": 11, "sales_amt": "409.480", "sales_from": null, "sales_to": null }] it is not including the fields of Outlet and Channel tables