Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have used djangorest to create an api but when i make a post request it returns an error saying 400 BAD request
this is the serializer : class PostSerializer(serializers.ModelSerializer): def create(self, validated_data): post = Post.objects.create( author=validated_data["author"], title=validated_data["title"], text=validated_data["text"] ) post.save() return post class Meta: model = Post fields = ["author", "title", "text", "pk", 'publicationDate'] this is the api view : class PostList(GenericAPIView, ListModelMixin, CreateModelMixin): queryset = Post.objects.all() serializer_class = PostSerializer def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) and this is the request I`m making : axios.post('/api/posts/', form, { "headers": { 'Content-Type': 'application/json', } }) .then(response => console.log(response.data)) this is the error it returns POST http://127.0.0.1:8000/api/posts/ 400 (Bad Request) I have been at this problem for days now and i have tried everything but it just wont work -
How to pass a javascript variable in html to views.py?
I am currently trying to make an website using django. And i faced a problem like i wrote in title. What i want to make is like this, first of all, shop page shows all products. But, when a user select a brand name on dropdown menu, shop page must shows only that brand products. To do this, i have to get a variable which a user select on dropdown menu, and my view function should run at the same time. Please let me know how can i resolve this. i made a dropdown in html as below. <shop_test.html> <form action="{% url 'shop' %}" method="get" id="selected_brand"> <select name="selected_brand" id="selected_brand"> <option value="ALL">Select Brand</option> <option value="A">A_BRAND</option> <option value="B">B_BRAND</option> <option value="C">C_BRAND</option> </select> </form> <script type="text/javascript"> $(document).ready(function(){ $("select[name=selected_brand]").change(function () { $(".forms").submit(); }); }); </script> and my views.py is as below. def ShopView(request): brand_text = request.GET.get('selected_brand') if brand_text == None: product_list = Product.objects.all() elif brand_text != 'ALL': product_list = Product.objects.filter(brand=brand_text) else: product_list = Product.objects.all() context = { 'brand_text': brand_text, 'product_list': product_list, } return render(request, 'shop_test.html', context) i tried to google it a lot of times, but i counldn't resolve this. -
I am facing issue in image uploading through API in django
class ResidenceAreaImage(APIView): def post(self, request): if request.FILES.get("image", None) is not None: img = request.FILES["image"] img_extension = os.path.splitext(img.name)[1] save_path = "/media/company_logo/" # if not os.path.exists(save_path): os.makedirs(os.path.dirname(save_path), exist_ok=True) img_save_path = "%s%s%s" % (save_path, str(uuid.uuid4()), img_extension) with open(img_save_path, "wb+") as f: for chunk in img.chunks(): f.write(chunk) # data = {"success": True} else: raise Exception("plz add image!!!") return Response({"file_url":img_save_path}) -
Why Django can't find static folder in BASE_DIR?
I have these directories: └── MY_FOLDER ├── MY_PROJECT │ └── settings.py │ ├── MY_APP ├── STATIC │ └── style.css ├── MEDIA └── manage.py In the settings.py I've indicated: BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = 'static/' STATICFILES_DIR = (os.path.join(BASE_DIR,'static')) When I print(STATICFILES_DIR) I get a path: MY_FOLDER/STATIC - what is exactly I wanted. But Django don't see any css there, in that folder. I tried to put my css to MY_APP/STATIC and it started to work correctly. But I want to have it not in MY_APP but in BASE_DIR/STATIC. How to do it? Or if it is impossible, how to make a correct path for STATICFILES_DIR to let it search my statics in all apps I'll add in the future. Not only in one app by doing this: STATICFILES_DIR = (os.path.join(BASE_DIR,'MY_APP','static')) Thanks. -
Auto import suggestion django functions in Vscode
hello everyone I am having a problem the visual studio code autoimport suggestion for django functions does not work for me. I appreciate the help. enter image description here pylance don't search in the django modules -
How can I set and append in column with conditional case in Django?
I want to run this sql query in Django UPDATE `TABLE` SET `COLUMN` = (CASE WHEN `COLUMN` = "" THEN '100' ELSE CONCAT(`COLUMN`,'100') END) WHERE `ID` IN [id1,id2,id3]; I tried this from django.db.models import Case, When, F Table.object.filter(id__in=[id1,id2,id3]). update(column= Case( When(column="",then="100"), default= column + "100", ) ) I dont know how to put concat in default here. Please help. -
django how should I create my multiple user
I have two different users, one requesting for repairs (Office) and the inspector/repairman which is (Technician). I was wondering if this is a good idea to make both officeid/techid in customUser like this or there's a better way this is the values of both office and technician, We have hr/accounting for example then EMP-** this is my full erd so far I might change somethings based on your recommendations -
Django Admin is not allowing me to change any user settings after implementing a AbstractUser
Following a video on Youtube I want to creat a website with different Roles for students and teachers. I also would like to save off the School ID in to the user. Here is what I want to change but when I hit save it does nothing. I've tried creating custom forms to use for the create and change but it doesn't seem to matter. I feel like I missed typed something in the model.py or I'm missing something. Creating users works like a charm so that's why I'm confused why it wouldn't update a user correctly. I have done a fully custom user class before but shouldn't need to for this simple of change. In the setting is have this line AUTH_USER_MODEL = "account_app.User" models.py from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db.models.signals import post_save from django.dispatch import receiver class School(models.Model): name = models.CharField('School Name', max_length=240) address1 = models.CharField('Address 1', max_length=240) address2 = models.CharField('Address 2', max_length=240) city = models.CharField('City', max_length=240) district = models.CharField('District', max_length=240) state = models.CharField('State', max_length=2) zip_code = models.IntegerField('Zip Code') country =models.CharField('Country', max_length=240) phone = models.IntegerField('School Phone Number') time_zone = models.CharField(max_length=50) def __str__(self): return f'{self.name}' class User(AbstractUser): class Role(models.TextChoices): ADMIN = "ADMIN", "Admin" STUDENT … -
Filtering Data from Firestore in Django, passing to HTML template
I have data stored in Firestore and i would like to get data from a collection, filter it and publish it in HTML template. I am using Django as the framework. VIEWS.py from django.shortcuts import render import pyrebase from firebase_admin import firestore import datetime db = firestore.Client() config = { "apiKey": "xxxxxx", "authDomain": "xxxxxx.firebaseapp.com", "databaseURL": "https://xxxxxx.firebaseio.com", "projectId": "xxxxxx", "storageBucket": "xxxxxx.appspot.com", "messagingSenderId": "xxxxxx", "appId": "xxxxxx", "measurementId": "xxxxxx", "serviceAccount": "xxxxxx.json", } # DATABASE firebase = pyrebase.initialize_app(config) authe = firebase.auth() database = firebase.database() print(database) # TIME & DATE today_date = datetime.datetime.now() tomorrow_date = today_date + datetime.timedelta(days=1) games_today = today_date.strftime("%Y-%m-%d") games_tomorrow = tomorrow_date.strftime("%Y-%m-%d") print(games_today) print(games_tomorrow) # NBA EVENT DATA def xxxxx_basketball_nba_events(request): nba_events = db.collection('xxxxx_au').document('basketball_nba').collection('event_info').stream() event_info = [doc.to_dict() for doc in nba_events] nba_games = sorted(event_info, key=lambda k: k['event_start'], reverse=True) print(nba_games) return render(request, 'html/nba.html', {'data': nba_games}) HTML template {% block content %} <table class="table table-striped" style="padding: 15px; width: 1000px"> <thead> <tr> <th scope="col">Event ID</th> <th scope="col">Competition</th> <th scope="col">Event Name</th> <th scope="col">Event Start</th> <th scope="col">Event Status</th> </tr> </thead> {% for xxx_nba in data %} <tbody> <tr> <th>{{xxx_nba.event_id}}</th> <td>{{xxx_nba.competition}}</td> <td>{{xxx_nba.event_name}}</td> <td>{{xxx_nba.event_start}}</td> <td>{{xxx_nba.event_status}}</td> </tr> </tbody> {% endfor %} </table> {% endblock %} HTML Output 1018936256 NBA Los Angeles Lakers - Portland Trail Blazers 2022-12-01T03:30:00Z NOT_STARTED 1018936251 NBA Sacramento Kings … -
Django nested model formsets only save the first form
I have two formsets that I created with modelsetfactory. When I give the extra field manually, it saves all the forms. But when I add a form dynamically, it only saves the first form. Before using nested formset, I did not encounter such an error, but I had to redesign my first form as a formset. As seen in the picture, it saves only the first of the forms that I add dynamically. Saves "Test Product" but not "Test Product 2" here is my models : class UserTask(models.Model): id = models.AutoField(primary_key=True) user_id = models.ForeignKey(User,on_delete= models.CASCADE, verbose_name='User',null=True, related_name="user_id") task_types_id = models.ForeignKey(TaskTypes,on_delete=models.CASCADE,verbose_name="Task Type", default=None) subunit_id = models.ForeignKey(WorksiteSubunit,on_delete= models.CASCADE,verbose_name="Subunit",null=True, default=None) store_house_id = models.ForeignKey(StoreHouse,on_delete= models.CASCADE,verbose_name="Store House",null=True) description = models.TextField(max_length=255) author = models.ForeignKey(User,on_delete= models.CASCADE,null=True, related_name="author_id") class TaskSources(models.Model): id = models.AutoField(primary_key=True) user_task_id = models.ForeignKey(UserTask,on_delete=models.CASCADE) product_id = models.ForeignKey(Product,on_delete=models.CASCADE,verbose_name="Product",null=True) product_amount = models.FloatField(max_length=255,verbose_name="Product Amount",null=True) def __str__(self): return str(self.user_task_id.store_house_id) here is my forms : class UserTaskForm(forms.ModelForm): class Meta: model = UserTask fields = ['user_id','task_types_id','store_house_id','description'] class TaskSourcesForm(forms.ModelForm): class Meta: model = TaskSources fields = ['product_id', 'product_amount'] TaskSourcesFormSet = modelformset_factory( TaskSources, fields=('product_id', 'product_amount',), extra=1, ) UserTaskFormFormSet = modelformset_factory( UserTask, fields=('user_id','task_types_id','store_house_id','description',), extra=1, ) here is my views : @login_required(login_url="login") def addUserTask(request): user_task_form = UserTaskFormFormSet(queryset=UserTask.objects.none(),initial=[{'user_id': request.user}]) formset = TaskSourcesFormSet(queryset=TaskSources.objects.none()) if request.method == 'POST': user_task_form … -
Enter a valid date/time - Django Datetime Picker
I'm creating a CRUD application in Django, and one of the fields in the data requires the user to enter a datetime input. This was working smoothly until this evening when I started to work on it again, however I'm getting the below error when I try to add any data the the model. start_datetimeEnter a valid date/time. [01/Dec/2022 00:34:39] "POST /activities/new/ HTTP/1.1" 200 2253 I've tried quite a few ways to resolve this but nothing seems to be working; below if the code I have to create the activity class ActivityForm(forms.ModelForm): class Meta: model = Activity fields = ('name', 'start_datetime', 'end_time', 'location', 'town', 'description') labels = { 'name': 'Activity Type', 'start_datetime': 'Date & Time of Activity', 'end_time': 'End Time', 'location': 'County', 'town': 'Town (optional)', 'description': 'Description', } widgets = { 'start_datetime': DateTimePickerInput(), 'end_time': TimePickerInput(), } class DateTimePickerInput(forms.DateTimeInput): input_type = 'datetime-local' This is the model field for the start_datetime: start_datetime = models.DateTimeField() Does anyone have any ideas on how to resolve this? Thanks! -
How to add a select element to a table (add object to m2m relation)
I have two manytomany related models Projects and Users. I would like that when selecting a user from the list, it would be added to the table, that is (user.member.add(project)). Would UpdateView help me? How? [enter image description here](https://i.stack.imgur.com/Be5w2.png) I thought about doing it by editing the psot method of UpdateView to add the relationship but I don't need data to be loaded in any form, I just want it to be inserted into the table and transparent to the user -
why Index error at / list index out of range?
hello im having a problem with the index code in my views.py, aparrently the HTML index is out of range for some reason i dont understand, because before i wanted to make the page to add images as avatars work perfectly fine the index .html is in a templates folder , inside the APP folder, and i created a media folder outside of the APP for storage of media this is the views.py from django.http import HttpResponse from django.shortcuts import render from django.views.generic import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import UpdateView, DeleteView, CreateView from django.contrib.auth.views import LoginView, LogoutView from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from .forms import PosteoForm, SignUpForm, UserEditForm from .models import Posteo, Avatar from django.urls import reverse_lazy # Create your views here. def mostrar_index(request): imagenes = Avatar.objects.filter(user=request.user.id) return render(request, 'index.html', {'url': imagenes[0].images.url}) def mostrar_gallery(request): return render(request,'gallery.html') def mostrar_contact(request): return render(request,'contact.html') def cursoPost(request): return render(request,'Posts.html') @login_required def crear_post(request): if request.method == 'POST': posteo = PosteoForm(request.POST) print('posteo') if posteo.is_valid(): data = posteo.cleaned_data posteo = Posteo (titulo=data['titulo'], texto=data['texto']) posteo.save() return render(request,'index.html') else: posteo = PosteoForm() print('formulario') return render(request,'Posts.html',{'posteo':posteo}) def buscar_post(request): return render(request,'buscador.html') def buscador (request): if request.GET.get ('titulo', False): titulo = request.GET ['titulo'] post = Posteo.objects.filter(titulo__icontains=titulo) return … -
Upload picture with ajax in django application
I'm stuck with a problem in a django application. I have an ajax function to upload a single image to a model but, so far, I wasn't able to succeed in my goal. What I basically achieve is that I get the file from Ajax but, when I try to send it on my Django request in the view, the result is None object. Let me post some code to be more clear: HTML: {% for question in questions %} <tr> <td>{{forloop.counter}}</td> <td>{{question.id}}</td> <td>{{question}}</td> <td> <a title="{% trans "Edit Question" %}" class="btn btn-warning btn-sm" href="{% url 'administration:edit_question' pk=question.id %}"><i class="fas fa-edit"></i></a> <a title="{% trans "See Details" %}" class="btn btn-primary btn-sm ms-3" href="{% url 'administration:question_details' pk=question.id %}" ><i class="fas fa-eye"></i></a> <a title="{% trans "Delete Question" %}" href="{% url 'administration:delete_question' pk=question.id %}" id="delete_question" class="btn btn-sm btn-danger ms-3"><i class="fas fa-trash"></i></a> <button title="{% trans "Add Image" %}" class="btn btn-sm btn-success ms-3" data-bs-toggle="modal" data-bs-target="#addImageModal{{question.id}}"><i class="fas fa-file-image"></i></button> {% if question.explanation %} <a title="{% trans "Edit Explanation" %}" href="{% url 'administration:edit_explanation' pk=question.explanation.id %}" class="btn btn-sm btn-info ms-3"><i class="fas fa-edit"></i></a> <button title="{% trans "Add Explanation Image" %}" data-bs-toggle="modal" data-bs-target="#addExplanationImageModal{{question.id}}" data-questionId="{{question.id}}" class="btn btn-sm btn-secondary explanationModals ms-3"><i class="fas fa-plus"></i></button> {% else %} <a title="{% trans "Add Explanation" %}" href="{% url … -
Django saving nested formsets that are related to each other column cannot be null error
There are two nested formsets and they are related to each other. When I increase the extra field in the second formset, I get the error column cannot be null. I have no problem saving both forms as one. Here is my error : The error Here is my forms : class UserTaskForm(forms.ModelForm): class Meta: model = UserTask fields = ['user_id','task_types_id','store_house_id','description'] class TaskSourcesForm(forms.ModelForm): class Meta: model = TaskSources fields = ['product_id', 'product_amount'] TaskSourcesFormSet = modelformset_factory( TaskSources, fields=('product_id', 'product_amount',), extra=2, ) UserTaskFormFormSet = modelformset_factory( UserTask, fields=('user_id','task_types_id','store_house_id','description',), extra=1, ) here is my views : @login_required(login_url="login") def addUserTask(request): user_task_form = UserTaskFormFormSet(queryset=UserTask.objects.none(),initial=[{'user_id': request.user}]) formset = TaskSourcesFormSet(queryset=TaskSources.objects.none()) if request.method == 'POST': user_task_form = UserTaskFormFormSet(request.POST) formset = TaskSourcesFormSet(request.POST) if user_task_form.is_valid(): for form in user_task_form: user_task = form.save(commit=False) user_task.author = request.user user_task.save() if formset.is_valid(): for form_data in formset: task_sources = form_data.save(commit=False) task_sources.user_task_id = UserTask(id = user_task.id) task_sources.save() messages.success(request,"Task added successfully!") return redirect(".") context = { "user_task_form" : user_task_form, "formset" : formset, } return render(request,"user/addtask.html",context) How to save two model formsets together(relates to each other) in one view? what is the wrong part when i do it? -
Multiple queries and chart js problem - Optimize Django hardcode
Hello mates. I have an project with patient laboratory analyses. The problem is my hardcoding but i didn't find the solution to make it simplier. My aim was to make a dataframe for each analysis group and draw chartjs. So let me explain what i did /w code: I have a patient analysis model: class PatientAnalysis(models.Model): patient = models.ForeignKey(Patient, related_name='analyses', on_delete=models.CASCADE) analysis_date = models.DateTimeField(default=datetime.now, help_text = "Разделяйте даты точками! Используйте '/' или '-'") # analysis_type = models.IntegerField(choices = ANALYSIS_CHOICES) #перевести в таблицу analysis_type = models.ForeignKey(AnalysisType, on_delete=models.CASCADE, default=1) analysis_data = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return f"{self.patient}" def get_analysis_type(self): return f"{self.analysis_type}" def get_absolute_url(self): return reverse('journal:patient_all_info', kwargs={'hist_num_slug':self.patient.pk}) class Meta: unique_together = ('analysis_date','analysis_type',) It has analysis type: class AnalysisType(models.Model): a_name = models.CharField(max_length=16) a_measur = models.CharField(max_length=16) a_ref_min = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) a_ref_max = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) analysis_group = models.ManyToManyField(AnalysysGroup) def __str__(self): return f"{self.a_name}" Which comes with Analysis group: class AnalysysGroup(models.Model): group_name = models.CharField(max_length=32) # analysis = models.ManyToManyField(AnalysisType, blank=True) def __str__(self): return f"{self.group_name}" I tried to show analyses for 1 person for each day and group it by type then draw chartjs multi table: def patient_filtered_analysis(request, pk, ag): patient_info = Patient.objects.get(pk=pk) analysis_group_list = AnalysysGroup.objects.all() analysis_group = AnalysysGroup.objects.filter(id=ag)[0] analysis_types_in_group = AnalysisType.objects.filter(analysis_group=ag) patient_filtered_analysis = PatientAnalysis.objects.filter(patient__hist_num=pk).filter(analysis_type__analysis_group=ag).order_by('analysis_type','-analysis_date') analysis_date_list … -
Consume a docker container inside Django docker container? Connecting two docker containers
I have a Django container and I want to consume another DL container inside it? For example, I have a Django app that predicting images classes and I want to make the prediction using a docker container and not a python library. That Django app will be containerised as well. In production, I will have three docker containers: Django container + Postgres container + YoloV5 container. How can I link the Django with the YoloV5 so that the prediction inside the Django will be done using the YoloV5? I want to connect a deep learning container with Django container to make prediction using the DL container and not a python package. -
Why swagger loading so long time and not answer
enter image description here views @swagger_auto_schema(request_body=BoardDetailSerializer, operation_summary="update method") def patch(self, request, pk): board = self.get_object(pk) serializer = BoardDetailSerializer(board, data=request.data, partial=True) if serializer.is_valid(): serializer.update() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers class BoardSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) title = serializers.CharField(max_length=30) background = serializers.ImageField(required=False, default=None) def create(self, validated_data): board = Board( title=validated_data['title'], background=validated_data['background'], ) board.save() return board def to_representation(self, instance): representation = super().to_representation(instance) representation['column'] = ColumnSerializer(instance.column.all(), many=True, context=self.context).data return representation [ 1. - --- ](https://i.stack.imgur.com/A4yjf.png) Idk what to do. I removed the 'Partial = True', and restarted patch request many time, but this is not workin. -
Django: Quizapp with Question and Answer Model
I would like to create a Quiz app with Django. Where the Questions can be stored in a DB and more users can add more questions in Admin. and each question can have an answer from the user input. This is a basic version of what I tried so far, Simple example of My Models: QuestionModel ID question author AnswerModel ID Answer question_id author So, When I create an AnswerForm(): it shows the form, but the question shows up as a dropdown instead of labels. and it is not creating fields for each question. It just creates one input field and a dropdown for the question. I know it does that because I have question_id as FK in the Answer Model. Is there a better way to get this done? I am new to Django -
Execute task at specific times django
I am in the process of writing my own task app using Django and would like a few specific functions to be executed every day at a certain time (updating tasks, checking due dates, etc.). Is there a way to have Django run functions on a regular basis or how do I go about this in general? Does it make sense to write an extra program with an infinite loop for this or are there better ways? -
Django convert InMemoryUploadedFile PDF to images
I need to convert uploaded PDF to images. I'm using pdf2image function convert_from_path() to convert the image but am getting an error Unable to get page count. My code looks somewhat like this: pages = convert_from_path(request.FILES['file'].read()) And the error: Error message Code line with error Is there a better way to do this? -
hey I want to create a freelancing web app like fiverr i want to know how to save payments on the website than withdraw them to visa or baknk
hey I want to create a freelancing web app like fiverr i want to know how to save payments on the website than withdraw them to visa or baknk hey I want to create a freelancing web app like fiverr i want to know how to save payments on the website than withdraw them to visa or baknk -
djangorestframework_camel_case (django parser library) does not work with multipart nested data
for eg. if post data is like: Postman Input then in view we get parsed data like: Output in Viewset settings.py: settings parameter I tried using parser_classes NestedMultiPartParser and CamelCaseMultiPartParser in ViewSet but no solution. -
how to compare two dictionaries and display the values that differs in template?
I try to compare two dictionaries and if on key, value differs from the other dictionary then print the difference key, value in red. I think my views.py is correct. But how to show the difference in the template? So I have views.py: def data_compare(): fruits = { "appel": 3962.00, "waspeen": 3304.07, "ananas": 24, } set1 = set([(k, v) for k, v in fruits.items()]) return set1 def data_compare2(): fruits2 = { "appel": 3962.00, "waspeen": 3304.07, "ananas": 30, } set2 = set([(k, v) for k, v in fruits2.items()]) return set2 def data_combined(request): data1 = data_compare() data2 = data_compare2() diff_set = list(data1 - data2) + list(data1 - data2) return render(request, "main/data_compare.html", context={"diff_set": diff_set}) and template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div class="container center"> {% for key, value in diff_set.fruits.items %} <span {% if key in data1.condition %} style="color: red;" {% endif %}>{{ key }}: {{value}}</span><br> {% endfor %} </div> <div class="container center"> {% for key, value in diff_set.fruits2.items %} <span {% if key in data2.condition %} style="color: red;" {% endif %}>{{ key }}: {{value}}</span><br> {% endfor %} </div> </body> </html> But nothing is returned. Question: how to return the key, … -
Serialize same level object from Many to many field
I have to serialize spare instance from spare variety many to many field. Models.py class SpareVariety(models.Model): quality = models.ForeignKey(Quality, max_length=255, on_delete=models.CASCADE, null=True, blank=True) variety_name = models.CharField(max_length=255, null=True, blank=True) property = models.ForeignKey(SpareProperty, null=True, blank=True, on_delete=models.CASCADE) purchase_price = models.PositiveIntegerField(help_text="in INR", blank=True, null=True) retail_price = models.FloatField(help_text="All values in INR", blank=True, null=True) dealer_price = models.FloatField(help_text="All values in INR", blank=True, null=True) stock_available = models.PositiveIntegerField(blank=True, null=True,default=True) spare_costing = models.ForeignKey(SpareCosting, on_delete=models.CASCADE, blank=True, null=True) spare_discount = models.ForeignKey(Discount, on_delete=models.CASCADE, blank=True, null=True) is_available = models.BooleanField(default=False) date_added = models.DateTimeField(auto_now=True) date_updated = models.DateTimeField(auto_now_add=True) class Spare(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) spare_variety = models.ManyToManyField(SpareVariety, related_name='spare_varieties', null=True, blank=True) name = models.CharField(max_length=255, help_text="Enter the name of spare (Ex:Display, Speakers)") type = models.ForeignKey(Type, blank=True, null=True, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now=True) date_updated = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.product.name, self.name) Serialize the spare model from spare variety serializer serializers.py class SpareVarietySerializer(serializers.HyperlinkedModelSerializer): spare_costing= SpareCostingSerializer(many=False, read_only=False) spare_discount = DiscountSerializer(many=False, read_only=False) quality = QualitySerializer(many=False, read_only=False) property = SparePropertySerializer(many=False, read_only=False) spare_name = serializers.CharField(read_only=True, source="spare.name") class Meta: model = SpareVariety fields = ['id','quality','variety_name','purchase_price','spare_name','retail_price','property', 'dealer_price', 'stock_available','spare_costing','spare_discount','is_available', 'date_added', 'date_updated',]