Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiply Django field values to get a total
I have the following models: class Supplier(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True, blank=True) email = models.CharField(max_length=200, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) class Meta: ordering = ('name',) def __str__(self): return self.name class Order(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.supplier.name @property def total(self): orderitems = self.product_set.all() total = sum([item.get_total for item in products]) return total class Product(models.Model): description = models.CharField(max_length=30) costprice = models.FloatField(null=True, max_length=99, blank=True) retailprice = models.FloatField(null=True, max_length=99, blank=True) barcode = models.CharField( null=True, max_length=99, unique=True, blank=True) supplier = models.ForeignKey( Supplier, on_delete=models.CASCADE, default=5) on_order = models.ForeignKey( Order, on_delete=models.CASCADE, null=True, blank=True) on_order_quantity = models.FloatField(null=True, blank=True) class Meta: ordering = ('description',) def __str__(self): return self.description i've created an order object for a given supplier with two products, with different quantities and cost prices. How do I multiply cost x qty and add up those values in order to reach a total order value? this is my view def PurchaseOrder(request, pk_order): orders = Order.objects.get(id=pk_order) products = Product.objects.filter( on_order_id=pk_order).prefetch_related('on_order') total_products = products.count() supplier = Product.objects.filter( on_order_id=pk_order).prefetch_related('on_order') total_value = Product.objects.filter( on_order_id=pk_order).aggregate(Sum('costprice')) context = { 'supplier': supplier, 'products': products, 'orders': orders, 'total_products': total_products, 'total_value': total_value, } return render(request, 'crmapp/purchase_order.html', context) at the moment it returns this: -
Issue with Django service worker: Uncaught SyntaxError: Unexpected token '<'
I try to add service worker to my app. But got an error Uncaught SyntaxError: Unexpected token '<' using debug tool, the first line <!doctype html> is underline for each files with error message I coul not find anywhere explaination for that... hope someone could help -
Bootstrap Accordion with django-tables2 SingleTableMixin
I am trying to create a bootstrap accordion with a django-table2 SingleTableMixin FilterView. The advantage for me with SingleTableMixin is that I can use the ExportMixin. The model has the fields, options and longtext, which I want to display under each row if clicked. view.py class MasterReportList(SingleTableMixin,LoginRequiredMixin, ExportMixin,FilterView): export_formats = ['csv', 'xlsx'] table_class = MasterReportTable #model = MasterReportData filterset_class = MasterReportFilter template_name = 'masterreport.html' paginate_by = 25 table.py class MasterReportTable(tables.Table): class Meta: model = MasterReportData #exclude = ("id","from_file", "exported_at","created_at" ) My question is, how can I access single, specific columns inside the custom template? -
DJANGO: How to create a method that copies an object of a model?
I want to create a method that copies an object of the BlogPost model. my models looks like this: class BlogPost(models.Model): title = models.CharField(max_length=250) body = models.TextField() author = models.ForeignKey(Author, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) def copy(self): pass class Comment(models.Model): blog_post = models.ForeignKey( BlogPost, on_delete=models.CASCADE, related_name="comments" ) text = models.CharField(max_length=500) my challenge is implementing the copy method. The copy method should copy the current object with all the comments related to that and I don't have any idea how to do it. -
TypeError: expected str, bytes or os.PathLike object, not InMemoryUploadedFile
I am getting following error when I am trying to upload image for predictive model- Exception Value: expected str, bytes or os.PathLike object, not InMemoryUploadedFile Exception Location: /Users/ragnar/plant-disease-recognition/lib/python3.8/site-packages/keras_preprocessing/image/utils.py in load_img, line 113 views.py class Predict(generics.CreateAPIView): serializer_class = ImageSerializer def post(self, request): """ post: API to send leaf image and get its health status or disease. """ data = ImageSerializer(data=request.data) if data.is_valid(): photo = request.data['photo'] img = image.load_img(photo, target_size=(224, 224)) img = image.img_to_array(img) img = np.expand_dims(img, axis=0) img = img/255 with graph.as_default(): prediction = model.predict(img) prediction_flatten = prediction.flatten() max_val_index = np.argmax(prediction_flatten) result = output_list[max_val_index] return Response({'result': result}) -
django switch databse user on each subdomain in the same app
i want to make a django application and for a security reasons, i have three types of users (admins, teachers , and students) i want to make a subdomain for each type of users users.domain.com teachers.domain.com admins.domain.com after the loggin i want to switch to a specific database user for each subdomain (the same database) I m new to django and i want some help to do this Thanks -
Deploy django with apache, django channels 3 and daphne in wss
Os Ubuntu 20 LTS i have a problem with my project in production, and i don't understand where and whats it's going wrong, thease are the files and the responses: 000-default.conf: <VirtualHost *:80> ..... RewriteEngine on RewriteCond %{SERVER_NAME} =site.addns.org [OR] RewriteCond %{SERVER_NAME} =www.site.addns.org RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC,OR] RewriteCond %{HTTP:CONNECTION} ^Upgrade$ [NC] RewriteRule .* wss://%{SERVER_NAME}%{REQUEST_URI} [P,QSA,L] ProxyPass /wss/ wss://127.0.0.1:8000/ ProxyPassReverse /wss/ wss://127.0.0.1:8000/ </VirtualHost> <VirtualHost *:443> ..... ProxyPreserveHost On SSLProxyEngine on SSLProxyVerify none SSLProxyCheckPeerCN off SSLProxyCheckPeerName off RewriteEngine on RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC,OR] RewriteCond %{HTTP:CONNECTION} ^Upgrade$ [NC] RewriteRule .* ws://127.0.0.1:8000%{REQUEST_URI} [P,QSA,L] ProxyPass /wss/ wss://127.0.0.1:8000/ ProxyPassReverse /wss/ wss://127.0.0.1:8000/ </VirtualHost> asgi.py: import os from django.urls import re_path, path from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "produzione.settings") django_asgi_app = get_asgi_application() from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.routing import get_default_application from principale import consumers application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AuthMiddlewareStack( URLRouter([ path(r'wss/$', consumers.EchoConsumer.as_asgi()), path(r'ws/chat/$', consumers.EchoConsumer.as_asgi()), ]) ), }) consumers.py: import json from channels.generic.websocket import WebsocketConsumer from channels.consumer import AsyncConsumer class EchoConsumer(WebsocketConsumer): def connect(self): self.accept() settings.py: ... ASGI_APPLICATION = "produzione.asgi.application" CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 8000)], }, }, } ... js file: var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"; var chat_socket … -
How to get username in form automatically in Django Forms?
I want to create a basic comment part for my project. But I cannot figure out how can I get username with forms. I tried to use initial but it did not work. How can I fix it? view.py def ocr(request, id): ... if request.method == 'POST': form_2 = CommentForm(request.POST, request.FILES, instance=pdf) if form_2.is_valid(): initial = {'username': request.user.username} form_2 = CommentFromOthers(initial=initial) form_2.save() else: form_2 = CommentForm() ... models.py class CommentFromOthers(models.Model): comp_name = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True) doc_id = models.ForeignKey(Pdf, on_delete=models.DO_NOTHING, null=True) comments = RichTextField(blank=True) created_date = models.DateTimeField(default=datetime.now()) username = models.CharField(max_length=250, default='') forms.py class CommentForm(forms.ModelForm): comments = RichTextField class Meta: model = CommentFromOthers fields = ('comments',) -
How to store and Retrieve List in database Django
I am trying to store the python List data type value into DB. Please find the below code I am using. Model.py class Counter(models.Model): myList = models.TextField(null=True) # JSON-serialized (text) version of your list views.py import simplejson as json def CTS_upload(request): -----Some logic--- myModel = Counter() listIWantToStore = [0,] -------Some code logic----- i = i + 1 count.append(i) listIWantToStore.append(i) myModel.myList = json.dumps(listIWantToStore) Problem: here each time when I am uploading a .xls file a new list object is getting created. I want changes to happen in the same existing List. Please find the below image. problem2: When I am trying to decode I am getting the below error. Exception Type: TypeError Exception Value: Input string must be text, not bytes def countclear(request): jsonDec = json.decoder.JSONDecoder() myPythonList = jsonDec.decode(Counter().myList) print(type(myPythonList)) print(myPythonList) ------Remaining code--- Any help on this how to create OR edit existing and retrieve values would be very helpful. -
Django - Adding permissions to user group during migration
I have a user group which I'm trying to add permissions to during migration using migrations.RunPython, such that the group is automatically created with appropriate permissions. I have a multi tenant app and would like those groups made upon creation of a new tenant. Creation of groups and permissions works fine but when I try to add a permission to a group that change is not applied after migration is finished. Here's my current code, I already applied some solutions from other questions I found but so far none of them work: portal/migrations/0003_add_group_perms.py def add_group_permissions(apps, schema_editor): db_alias = schema_editor.connection.alias try: emit_post_migrate_signal(2, False, 'default') except TypeError: # Django < 1.8 emit_post_migrate_signal([], 2, False, 'default', db_alias) Permission = apps.get_model("auth", "Permission") Group = apps.get_model("auth", "Group") for group in usergroup_permissions: role, created = Group.objects.get_or_create(name=group) logger.info(f'{group} Group created') for perm in usergroup_permissions[group]: role.permissions.add(Permission.objects.get(codename=perm)) logger.info(f'Permitting {group} to {perm}') role.save() class Migration(migrations.Migration): dependencies = [ ('portal', '0002_import_groups'), ] operations = [ migrations.RunPython(add_group_permissions), ] the usergroup_permissions variable looks like this and contains permission codenames: usergroup_permissions = { "Administrator": [ "add_user", "delete_user", ], When starting the development server I can then see, that the permissions are not applied to group administrator: screenshot I'm using django 3.1.6 and django-tenants 3.2.1 … -
How can I apply grammatical gender in Choices?
I use Model Utils to define statuses in Django : class MetaData(TimeStampedModel, StatusModel, SoftDeletableModel): STATUS = Choices(('Draft', _('Draft')), ('Submitted', _('Submitted')), ('Reviewed', _('Reviewed')), ('Final', _('Final')),) These statuses may eventually apply to a masculine or feminine object (in French), and I don't understand how to define pgettext contexts here. Thank you very much ! -
Django ORM using cursor to memory optimize QuerySets
Is there any way to convince Django ORM to use a database cursor when iterating through a large QuerySet so that it does not load all the objects at once but load them by parts instead? -
DRF- Many to many through model serialization issue
I can't not get the serialised response from create method of profileserializer, it successfully creates the object but while returning serialised reponse, it tries to access the attribute of m2m field instead of throughmodel and shows error mentioned below: The serializer field might be named incorrectly and not match any attribute or key on the State instance. Original exception text was: 'State' object has no attribute 'state'. Models and serializers details are given below. class State(CommonModel): name = models.CharField(max_length=100) code = models.CharField(max_length=2) def __str__(self): return str(self.name) class Profile(CommonModel): states = models.ManyToManyField(State, related_name=“profile_states, through='ProfileStates', through_fields=('profile', 'state', 'license_type'), blank=True) class ProfileStates(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE) state = models.ForeignKey(State, on_delete=models.CASCADE) license_type = models.ForeignKey(LicenseType, on_delete=models.CASCADE, null=True) class Meta: db_table = "app_name_profile_licensed_states" unique_together = ("profile", "state", 'license_type') class ProfileStatesSerializer(serializers.ModelSerializer): class Meta: model = ProfileStates fields = ("state", "license_type") class ProfileSerializer(serialisers.ModelSerializer): states = ProfileStatesSerializer(models.ProfileStates.objects.all(), many=True) def create(): return instance I have tried adding related_name in serializer and remove states from required field like: class ProfileSerializer(serialisers.ModelSerializer): profile_states = ProfileStatesSerializer(models.ProfileStates.objects.all(), many=True) def create(): return instance def get_field_names(self, declared_fields, info): expanded_fields = super(ProfileSerializer, self).get_field_names(declared_fields, info) if getattr(self.Meta, 'extra_fields', None): return expanded_fields + self.Meta.extra_fields else: return expanded_fields class Meta: model = models.Profile fields = ("__all__") extra_fields = [‘profile_states'] extra_kwargs = … -
Form is returning invalid for username value
I am trying to submit a username as default value for a model form but after submitting the value field turns blank after submit. Hence the form doesn't validate. This is my form: class WeeklyForm(ModelForm): class Meta: model = wreport fields = [ 'tname' ,'classes', 'fdate', 'tdate', 'objective', 'tplan', 'how', 'material', 'extra'] required = False widgets = { 'tname' : TextInput(attrs= {'class' : 'form-control', 'disabled' : True}), 'classes' : Select(attrs= {'class' : 'form-control'}), 'fdate' : DateInput(attrs= {'class' : 'form-control'}), 'tdate' : DateInput(attrs= {'class' : 'form-control'}), 'objective' : Textarea(attrs= {'class' : 'form-control'}), 'tplan' : Textarea(attrs= {'class' : 'form-control'}), 'how' : Textarea(attrs= {'class' : 'form-control'}), 'material' : Textarea(attrs= {'class' : 'form-control'}), 'extra' : Textarea(attrs= {'class' : 'form-control'}), } This is my view: @login_required(login_url='login') def weekly(request): context = '' weekly_form = WeeklyForm() daily_form = DailyForm() if request.method == 'POST' and 'weekly' in request.POST: initial = {'tname' : request.user.username} form = WeeklyForm(request.POST or None, initial = initial) # print(form['tname']) if form.is_valid(): # print(form) # form.save(commit=False) # form.tname = request.user.username form.save() # print(form.tname) messages.success(request, "Your report was submitted Successfully.") else: messages.error(request, form.errors) # print(form.errors) else: initial = {'tname' : request.user.username} weekly_form = WeeklyForm(initial = initial) I have tried sending value from form via kwargs but … -
How to display sum of disctinct items in django?
I would like to display sum all the distinct categories of the products that belongs to the user. I searched on the web, but all the things that I tried doensn't work. You may find the models,view and template below. It doesn't give me anything at the html. Model: class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,related_name='products') category = models.CharField(max_length=120) brand = models.CharField(max_length=120) product = models.CharField(max_length=120) price = models.DecimalField(decimal_places=2,max_digits=100) class Comp_Product(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE, related_name="comp_products") competitor = models.URLField() price = models.DecimalField(decimal_places=2,max_digits=100) change = models.FloatField() stock = models.BooleanField() last_update = models.DateField(auto_now_add=True) View: class DashboardList(ListView): template_name='dashboard_by_user.html' def get_queryset(self): return Product.objects.filter(user=self.request.user).annotate(count_category=Count('category',distinct=True)).aggregate(sum_category=Sum('count_category')) template: {% for product in product_list %} {{product.sum_category}} {%endfor%} -
How to filter database table using link <a href=''> in django?
I try to show a page with posts from that category when the user clicks on a link to a certain category This is mine urls.py file: from django.urls import path from .views import PostHomeView,PostDetail,NavFooter,PostPageView urlpatterns = [ path('navbar', NavFooter, name='Nav_Footer'), path('', PostHomeView.as_view(), name ='home'), path('PostDetail/<int:pk>', PostDetail.as_view(), name ='post_detail'), path('PostPage/', PostPageView, name ='post_page'), ] This is mine view.py file from django.shortcuts import render from django.http import HttpResponse from django.views.generic import ListView,DetailView from .models import Post, TaskCategory def NavFooter(request): return render(request,"nav_footer.html", {}) class PostHomeView(ListView): model = Post context_object_name = 'post' template_name = 'home.html' def get_queryset(self): return Post.objects.order_by('task_title')[:9] def PostPageView(reguest): posts = Post.objects.all() category = TaskCategory.objects.all() return render(reguest,'post_page.html',{'posts':posts,'category':category}) class PostDetail(DetailView): model = Post template_name = 'post_detail.html' This is models.py file: from django.contrib.auth.models import User from django.db import models class TaskCategory(models.Model): category_title = models.CharField(max_length=50) def __str__(self): return self.category_title class Post(models.Model): task_category = models.ForeignKey(TaskCategory, on_delete=models.CASCADE) recommended_tools = models.CharField(max_length=250) budget = models.CharField(max_length=250) def __str__(self): return self.task_title + ' | ' + self.task_discription + ' | ' + str(self.task_category) + ' | ' + self.recommended_tools + ' | ' + self.budget The fastest way to access this file via html -
django CBV's CreateView upload image into the folder that is created by object id
How do I, in class-based views CreateView can implement upload logic. I would like to first save the object, get its saved id, Then gets that object back, Update the folder_name field Once it's done I would like to upload the file to that newly created folder. Plus any suggestions on the code below: class MemberCreateView(PermissionRequiredMixin, CreateView): raise_exception = False permission_required = 'members.add_member' redirect_field_name = 'next' model = models.Member form_class = AddMember template_name = 'members/create.html' # success_url = '/members/' def get_initial(self, *args, **kwargs): initial = super().get_initial(**kwargs) # initial['name'] = 'Add a name' return initial def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super(ModelFormMixin, self).form_valid(form) def get_success_url(self): current_id = self.object.id memb = models.Member.objects.get(pk=current_id) memb.folder_name = str(current_id) + "_" + slugify(self.object.name) memb.save() return '/members/'+str(current_id) + "/add_family/" any suggestions on how can I improve my code Regards -
Django permissions: custom logic-based checks
Simplified example: # foo/models.py class Bar(models.Model): author = models.ForeignKey(User) # foo/views.py class BarEditView(PermissionRequiredMixin, UpdateView): permission_required = 'foo.change_bar' model = Bar success_url = '/' I want the BarEditView to be accessible by: users who have foo.change_bar permission in the database (already accomplished by the first line of that class) the author of that particular Bar record The first is easily handled by basic permissions/groups. How do I achieve the second? I need to write some custom permission check logic, but I can't find anything in the docs or google. I don't want to have to "manually" add a permission to the database every time a Bar author is set/changed/removed. To be clear, I am not asking how to create a "custom permission". I want am trying to augment the logic for determining who has permission. -
How does one log in multiple users in django
Am developing a school management system using Django. The project has got 5 apps, namely student, teacher, parent, blog and finance. The super admin an add, delete, update or edit students, parent, blog and finance (student school fees). How can i design the models so that the system can be used to log in different users and send them in different pages. For example when a student logs in should be redirected to the student dashboard while when a teacher logs in should be redirected to the teachers dashboard and for the super admin can access all the students and teachers. -
The HTML markup to include the image of Rango in the about template was not found
While creating a web app in Django, I've encountered a small issue. There seems to be a problem with my about template referencing. This is about.html: Here's my settings.py: And here's my urls.py: I'm getting an error saying: The HTML markup to include the image of Rango in the about template was not found. -
Disallow All Site Users From appearing In Post Form During Post Creation
The post rationale was to permit all clients on my site to have the option to make post and news which is a success however shockingly while making a post all the entire aunthenticated client/users in the data set shows up for the specific confirmed client to browse and this are data I don't need the client/users to see when making post and I have no arrangement to eliminate the users Foreignkey from the post Model since it encourages me actualizing other site basic capacities and the Author functions. since the users/client will fill in as creator/author class Post(models.Model): image = models.ImageField(upload_to="images/") title = models.CharField(max_length=150) summary = models.CharField(max_length=250) category = models.ForeignKey(PostCategory, on_delete=models.CASCADE) content = RichTextUploadingField() date_posted = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField(max_length=250, unique=True, blank = True) def onlyselfuser(self, *args, **kwargs): self.user = self.request.user super().onlyselfuser(*args, **kwargs) #please take a look at my view.py files class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = __all__ def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) i will appreciate if someone can show me a way out where the login user( user=request.user) will only appear excluding other users on moder and i tried a OneToOneField still and it didnt work. i Don't want … -
Integrating scrapy crawler with Django
Before you mark this as duplicate, please read ahead. I have researched much and haven't found anything (although a different question with the same title). In my project, I want to take a URL from the user and scrape the URL using a Scrapy spider/crawler. I first tried to do this by directly putting the scraper code in my views.py but the start/stop of twisted.internet.reactor was causing problems. Another method was to use a scheduling program such as Scrapyd. But the point is that the next operations in the particular view must happen only after the crawler has finished scraping. Scrapyd will only be scheduling the crawler. Please correct me if I am wrong about the assumption about Scrapyd or there is some API that I could use to track the progress of scraping. If not, suggest what I can do to achieve that. TIA. -
Two model fields and one form field in Django
I have two fields in Model and one form field. The widget AutocompleteInput is attached to form input. If the user selects an element from the autocompleteinput list in the widget, I want the data to be save to one field model. If the user enters their own string, I want the data to save to another field in the model. -
Django Model form not saving data to the database model on form submission
I have created a project and added models in the models and also created a form in forms.py. I am trying to modify some values using the commit=False. On submitting the form, it's not saving the data to the database and there is no error thrown from the code. I have no idea on how I can solve the issue. models.py from django.db import models from django.contrib.auth.models import User class Agent(models.Model): name = models.CharField(max_length=255) id_no = models.CharField(max_length=20) address = models.CharField(max_length=255) gender = models.CharField(max_length=8) age = models.IntegerField() agent_no = models.CharField(unique=True, max_length=12, null=True) email = models.EmailField(max_length=50) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.name}" class Company(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=255, null=True, blank=True) address = models.CharField(max_length=255, null=True, blank=True) telephone = models.IntegerField( null=True, blank=True) email = models.EmailField(max_length=50, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.name}" class Task(models.Model): company = models.ForeignKey(Company, null=True, on_delete=models.SET_NULL) agent = models.ForeignKey(Agent, null=True, on_delete=models.SET_NULL) cargo = models.CharField(max_length=200) document = models.FileField(upload_to='documents/') quantity = models.FloatField() amount = models.FloatField() duty = models.FloatField(null=True, blank=True) status = models.CharField(max_length=50, default='Pending') date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.cargo}" forms.py from django.contrib.auth.models import User from django import forms import re from django.core.exceptions import ValidationError from .models import * class TaskForm(forms.ModelForm): cargo = forms.CharField( required=False) document … -
Django Rest API- pass additional objects to ModelSerializer
I have a comment field for every blog post. I want to pass Comment.objects.all() from Views.py to ModelSerializer def get_comments(self, obj) to reduce the number of sql queries. As I am serializing a list of blog posts Views.py class BlogViewSet(ModelViewSet): queryset = Blog.objects.all().annotate( author_name=F('author__username') ) serializer_class = BlogSerializer permission_classes = [IsOwnerOrReadOnly] def list(self, request): return Response({'blogs': BlogSerializer(self.queryset, many=True).data}) Serializers.py class BlogSerializer(ModelSerializer): author_name = serializers.CharField(read_only=True) comments = SerializerMethodField() class Meta: model = Blog fields = ('title_text', 'main_text', 'datepublished', 'author_name', 'id', 'comments') def get_comments(self, obj): # filter comment comment_object = Comment.objects.filter(post_id=obj.id) comments = CommentSerializer(comment_object, many=True).data return comments