Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django filters form not showing
django filters form not showing it is supposed to show a form but only shows the submit button models.py: class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,null=True) bio = models.TextField() phone_number = models.IntegerField(blank=True, null=True) Birth_date = models.DateField(blank=True, null=True) age = models.IntegerField(blank=True, null=True) education = models.TextField(blank=True, null=True,max_length=45) WorkType = models.CharField(blank=True, null=True,max_length=150) desired_wage = models.IntegerField(blank=True, null=True) location = models.CharField(blank=True, null=True,max_length=25) gender = models.PositiveSmallIntegerField(blank=True, null=True,choices=GENDER_CHOICES) def __str__(self): return str(self.user) if self.user else '' views: def ListingsPage(request): Profile = Profile.objects.all() profile_filter = ProfileFilter(request.GET,queryset=Profile) profile = profile_filter.qs context = { "filter":profile_filter, "profile":Profile, } return render(request,"base/Listings.html",context) filters.py: import django_filters from .models import Profile class ProfileFilter(django_filters.FilterSet): class Meta: model = Profile fields = ['bio','location'] tempmlate: <div> <form method="GET" action="{% url 'listings' %}"> {{filter.form}} <button type="submit" value="Submit">Submit</button> </form> </div> It's supposed to show a form, it doesn't -
Optimizing serialization in Django
I've got the following models: class Match(models.Model): objects = BulkUpdateOrCreateQuerySet.as_manager() id = models.AutoField(primary_key=True) betsapi_id = models.IntegerField(unique=True, null=False) competition:Competition = models.ForeignKey(Competition, on_delete=models.CASCADE, related_name='matches') season:Season = models.ForeignKey(Season, on_delete=models.CASCADE, related_name='season_matches', null=True, default=None) home:Team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='home_matches') away:Team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='away_matches') minute = models.IntegerField(default=None, null=True) period = models.CharField(max_length=25, default=None, null=True) datetime = models.DateTimeField() status = models.IntegerField() opta_match = models.OneToOneField(OptaMatch, on_delete=models.CASCADE, related_name='match', default=None, null=True) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class Event(models.Model): objects = BulkUpdateOrCreateQuerySet.as_manager() id = models.AutoField(primary_key=True) betsapi_id = models.IntegerField(unique=True) name = models.CharField(max_length=255) minute = models.IntegerField() player_name = models.CharField(max_length=255, null=True, default=None) extra_player_name = models.CharField(max_length=255, null=True, default=None) period = models.CharField(max_length=255) team:Team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='events') match:Match = models.ForeignKey(Match, on_delete=models.CASCADE, related_name='events') updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self) -> str: return f"{self.betsapi_id} | {self.name} | {self.minute}" And the following snippet of my serializer: class TestMatchSerializer(serializers.Serializer): home = TeamSerializer(many=False, read_only=True) away = TeamSerializer(many=False, read_only=True) competition = CompetitionSerializer(many=False, read_only=True) events = serializers.SerializerMethodField() class Meta: model = Match fields = ['id', 'home', 'away', 'competition', 'status'] def get_events(self, instance : Match): events = instance.events.filter(name__in=["Corner", "Goal", "Substitution", "Yellow Card", "Red Card"]).order_by('-id') return EventSerializer(events, many=True).data When I serialize 25 objects using the following code including the events it takes about 0.72s. all_matches_qs = Match.objects.all().prefetch_related('statistics').select_related('home', 'away', 'competition', 'competition__country') TestMatchSerializer(all_matches_qs[:25], many=True, … -
DoesNotExist at /rooms/create_room/ Room matching query does not exist (showing error in different function than the one im executing)
DoesNotExist at /rooms/create_room/ Room matching query does not exist error showing in this line which is a different view function(which is working perfectly) than the one I'm executing in the current template room = Room.objects.get(slug=slug) The indicated function @login_required def room(request, slug): room = Room.objects.get(slug=slug) messages = Message.objects.filter(room=room) [0:25] return render(request, 'rooms/room.html', {'room': room, 'messages': messages}) The function I'm trying to execute for creating room model instance def room_form(request, id): if request.method == 'POST': cf = RoomForm(request.POST or None) if cf.is_valid(): name = request.POST.get('name') room = Room.objects.create(room = room, user = request.user, name = name) room.save() return redirect(room.get_absolute_url()) else: cf = RoomForm() context ={ 'room_form':cf, } return render(request, 'rooms/create_room.html', context) My model.py class Room(models.Model): user = models.ForeignKey(User,models.CASCADE) name = models.CharField(max_length=255) slug = models.SlugField(unique=True,blank=True) created = models.DateTimeField(auto_now_add=True, null=True) # slug = models.SlugField(max_length= 300,null=True, blank = True, unique=True) def __str__(self): return self.name + " | " + self.user.username def save(self, *args, **kwargs): self.slug = slugify(self.name + self.created.day) super(Room,self).save(*args, **kwargs) In my forms class RoomForm(forms.ModelForm): class Meta: model = Room fields = [ 'name', ] labels = { "name": "Room Name", } In my URLs urlpatterns = [ path('',views.rooms, name='rooms'), path('<slug:slug>/',views.room, name='room'), path('create_room/',views.room_form,name="create_room"), ] Im on a deadline and this weird error appeared … -
WebSocket connection getting rejected in production environment in docker container
My WebSocket connection getting rejected from the Django Channels server deployed in AWS EC2. I am using Docker for server side which contains PostgreSQL and Redis also WebSocket HANDSHAKING /ws/notifications/ WebSocket REJECT /ws/notifications/ WebSocket DISCONNECT /ws/notifications/ front-end is built using React Js is deployed in netlify. server side is secured using cer-bot. my nginx configuration files looks like this map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { server_name IP_address example.com ; location = /favicon.ico { access_log off; log_not_found off; } location /staticfiles/ { root /home/ubuntu/social-network-django-server; } location / { proxy_pass http://127.0.0.1:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/_____; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/____; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = example.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name IP_address example.com ; return 404; # managed by Certbot } everything other than the websocket connection is working fine without any issues. I have no idea what is happening here. I am using d]Django channels first time, I … -
Django ORM can't execute it's own raw query
I use Django with Postgres as my database. If I run this code: SomeClass.objects.filter(text__regex=rf"searchkeyword") the_query = str(SomeClass.query) The the_query variable will be this: SELECT * FROM "SomeClass" WHERE "SomeClass "."text"::text ~ searchkeyword But when you run this query using SomeClass.objects.raw(query), it will show this error: Exception Value: column "usa" does not exist ... WHERE "SomeClass"."text"::text ~* searchkeyword So, basically, Django ORM can't run the raw query that it made itself. Does anyone have any thoughts on this? First Edit: Even for simpler queries like this, I get the same error: SomeClass.objects.filter(text="searchkeyword") column "searchkeyword" does not exist LINE 1: SELECT * FROM SomeClass WHERE text = searchkeyword -
Getting a didn't return an HTTPResponse Object
I am creating a view in Django that will take user input based on inventory and link it to the different locations in which inventory is taken. When I try to get it up and running, I get the view inventory.views.inventory_entry didn't return an HttpResponse object. It returned None instead. Code below Views.py from django.shortcuts import render, redirect from .models import Location, Inventory from .forms import DataForm from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 def inventory_entry(request): if request.method == 'POST': form = DataForm(request.POST) if form.is_valid(): location = form.cleaned_data['location'] date = form.cleaned_data['date'] description = form.cleaned_data['description'] in_use = form.cleaned_data['in_use'] training_room = form.cleaned_data['training_room'] conference_room = form.cleaned_data['conference_room'] gsm_office = form.cleaned_data['gsm_office'] prospecting_station = form.cleaned_data['prospecting_station'] applicant_station = form.cleaned_data['applicant_station'] visitor_station = form.cleaned_data['visitor_station'] other = form.cleaned_data['other'] spare_on_floor = form.cleaned_data['spare_on_floor'] spare_storage = form.cleaned_data['spare_storage'] total_spare = form.cleaned_data['total_spare'] broken = form.cleaned_data['broken'] total = form.cleaned_data['total'] Inventory.objects.create(location=location, date=date, description=description, in_use=in_use, training_room=training_room, conference_room=conference_room, gsm_office=gsm_office, prospecting_station=prospecting_station, applicant_station=applicant_station, visitor_station=visitor_station, other=other, spare_on_floor=spare_on_floor, spare_storage=spare_storage, total_spare=total_spare, broken=broken, total=total) return redirect('data_entry') else: form = DataForm() locations = Location.objects.all() return render(request, "inventory/index.html", {'form':form, 'locations': locations}) Models.py from django.db import models OFFICE_CHOICES = ( ('Akron, OH', 'AKRON'), ('Atlanta, GA', 'ATLANTA'), ('Austin, TX', 'AUSTIN'), ('Birmingham, AL', 'BIRGMINGHAM'), ('Boston, MA', 'BOSTON'), ('Charleston, SC', 'CHARLESTON_SC'), ('Charleston, WV', 'CHARLESTON_WV'), ('Charlotte, NC', 'CHARLOTTE'), ('Chicago West, … -
How can I solve the TypeError
TypeError: function() argument 'code' must be code, not str from rest_framework.authtoken.views import obtain_auth_token from rest_framework.authtoken.models import Token class UserAuthentication(obtain_auth_token): def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['User'] token, created = Token.objects.get_or_create(user=user) return Response(token.key) -
Login with Google using django-alluath doesn't work correctly
I've implemented Google authorization using django-allauth, but it only works for users signed up with django-allauth and for users signed up with django the authorization doesn't work and redirects to the http://127.0.0.1:8000/social/signup/ with the message "Sign Up. You are about to use your Google account to login to localhost. As a final step, please complete the following form:". How can I allow users not registered with django-allauth to sign in with Google? -
Django profile pictures are not found in browser
TBH this is my first site to build, so lots of short comings expected, and the site is not expected to meet any standards, but I'm rather just playing around with the concepts to learn in my free time. The browser cannot locate my Profiles' profile pictures to render in the templates! saying (Url Not found). Template urls View Profile model I uploaded profile pictures to a few profiles but they wont show in the browser! -
Invalid parameters after copying a plugin in Dajngi CMS
I'm coding a website in Django CMS and I have a few plugins added. However, when I copy a plugin copying plugin and switch to another language via toolbar on top toolbar (either the current language or any other that was defined in settings.py file), I have the following error: error Does anyone know how to resolve the error? I have no idea why it is happening. However, the plugin was copied and if I go back to the home page (http://127.0.0.1:8000/en/) and choose a language again, then paste my plugin in, it will be inserted paste in. -
custom login with windows authentication in django
I got a custom user login using my own database to enter a web I created. The question is if is it possible to verifiy the user login with widnows authemtication, I appreciate your responses, thanks I search for login with windows auth and I only found login auth for admin page -
Is there a way to start huey with django and pass settings only related to huey?
When I start huey with manage.py it brings all the settings and logic from the current configuration class. Is there a way to pass only huey-related settings to huey? Something like python manage.py run_huey --configuration=HueyConfiguration Thanks. -
regex for finding a keyword from a sentence in python
I have written a piece of code for detecting if a keyword exists in a sentence. Following is my regex: re.search(r'\s'+keyword+r'\s', message, re.IGNORECASE)** There are following cases for which I want my regex to work: Let's take an example where keyword is hello we want this regex to work if the message is hello, my name is tia. i.e. the keyword comes in the beginning. it should also work, if the keyword comes in the end of the message like. my name is tia, hello. even if it comes in the middle, this should work fine like if the message is i am tia. hello. i love python. if there is a new line before or after our keyword, we expect the regex to work. i am tia. hello i love python. NOTE: it should only return true if there exists the whole keyword inside the sentence and not just a substring of the keyword. re.search(r'\s'+keyword+r'\s', message, re.IGNORECASE)** i have tried the above regex but it doesn't really seem to work. -
An editable table or form in Django (table like Excel) is online editable
Good day! I have a table model in Django . I am displaying the last 10 rows from this model in a simple table on the app. I really need to change this data in some kind of interface in a Django application. 10 table rows from the model. I'm looking for options as possible when clicking on a cell to make it possible to edit its contents. Just like in Excel spreadsheets. And at the end, click on the button and send the edited part to the Django internal part, to the model. I wanted to ask if anyone has such information on how to do something like this? I would be very grateful for any information. -
Optimize DjANGO's ORM
I am trying to display the post and all the comments of this post. Comments have likes, so their number also needs to be displayed. But it is not possible to optimize these queries. The problem is that django turns to vi every time to get author and quotes_comment_like from there to count the number of authors who have put likes. Models.py class QuotesHonors(models.Model): quotes = models.TextField() liked = models.ManyToManyField(Profile, related_name='likes_quotes', blank=True) editor = models.ForeignKey(Profile, on_delete=models.DO_NOTHING, related_name='quotes_editor') author = models.ForeignKey(Profile, on_delete=models.DO_NOTHING, related_name='quotes_author') category = models.ManyToManyField( 'Category', related_name='quotes_category') updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def number_comments(self): return self.quotes_comment.all().count() class Like(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='user_like') quotes = models.ForeignKey(QuotesHonors, on_delete=models.CASCADE, related_name='quotes_like') updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self) -> str: return f'"{self.user}" like "{self.quotes}"' class Comment(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='user_comment') quotes = models.ForeignKey(QuotesHonors, on_delete=models.CASCADE, related_name='quotes_comment') body = models.TextField(max_length=300) liked = models.ManyToManyField(Profile, related_name='likes_comment', blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def number_likes(self): return self.liked.all().count() def __str__(self) -> str: return f'"{self.user}" comment "{self.quotes}"' class CommentLike(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='user_comment_like') comment = models.ForeignKey(Comment, on_delete=models.CASCADE, related_name='comment_like') updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self) -> str: return f'"{self.user}" like comment "{self.comment}"' Views.py class QuotesDetail(DetailView): model = QuotesHonors template_name = 'quotes/quotes_detail.html' def get(self, request, … -
Django request.POST not passed to form.data
I have a form, but request.POST is not passing data to my form. i.e. form.data is empty my form class DPStatusForm(forms.Form): status = forms.ChoiceField(label="") def __init__(self, excluded_choice=None, *args, **kwargs): super().__init__(*args, **kwargs) if excluded_choice: status_choices = ( (s.value, s.label) for s in DP.Status if s.value != excluded_choice ) else: status_choices = ((s.value, s.label) for s in DP.Status) self.fields["status"].choices = status_choices view to receive form data def update_status(request, id): if request.method == "GET": return redirect("my_app:show_dp", id) p = get_object_or_404(DP, pk=id) form = DPStatusForm(request.POST) # debug statements print(request.POST) print(form.data) # ... With the 2 print statements, I can see that request.POST is present with status key populated, but form.data is empty: # request.POST <QueryDict: {'csrfmiddlewaretoken': ['xxx...], 'status': ['1']}> # form.data <MultiValueDict: {}> Why is form.data not getting populated? -
Create sqlalchemy engine from django.db connection
With DJANGO app and postgresql db, I use panda read_sql quite a bit for rendering complex queries into dataframe for manipulation and ultimate rendering to JSON. Historically have used django.db dbconnections to map from multi db environment and pass that connection directly into read_sql function. As panda evolves, and becomes less tolerant of non sqlalchemy connections as an argument, I am looking for a simple method to take my existing connection and use it to create_engine. I've seen some related past comments that suggest engine = create_engine('postgresql+psycopg2://', creator=con) but for me that generates an error: TypeError: 'ConnectionProxy' object is not callable I've played with various attributes of the ConnectionProxy...no success. Would like to avoid writing a separate connection manager or learning too much about sqlalchemy. Django is using psycopg2 to create its connections and I am long time user of same. Some of the add-ins like aldjemy are too intrusive since I neither need or want models mapped. Some have suggested ignoring warning message since dbconnection still works...seems like risk longterm... -
Count before filter in django
I have a ModelViewSet with their own filter. class XList(viewsets.ModelViewSet,): serializer_class = serializers.XXX queryset = models.XXX.objects.all() lookup_field = 'field_id' filter_backends = [DjangoFilterBackend] filterset_class = filters.MYOWNFILTER I want show in response the count of data before and after filtering. My desired answer would be, { "next": 2, "previous": null, "count": 20, "TOTAL_COUNT": 100 "size": 10, "results": [ {} ] } where TOTAL_COUNT would be the total count of data before any filter, and count, the count of data after filter. Now, I've got the following response. I need the total count. { "next": 2, "previous": null, "count": 20, "size": 10, "results": [ {} ] } I'm using pagination to get the response. def get_paginated_response(self, data): return Response({ 'next': self.page.next_page_number() if self.page.has_next() else None, 'previous': self.page.previous_page_number() if self.page.has_previous() else None, 'count': self.page.paginator.count, 'size': len(data), 'results': data -
How to make dynamic url on HTML form
I want to make web with django framework and postgres as the database. The web can add, delete and edit the table which connect with database. I've finished the add and delete button but I'm getting stuck with the edit button. I want to make edit button to edit a row data. When we click the edit button there will be a modal (like add button) that we will edit the selected row data. I use HTML form to make a form. My idea is when we click the edit button I want to collect the id of the row. So, after I submit the form to edit the data, the url redirect to /edit/int:id (urls.py) then triggered the edit function (views.py). My problem is on form action='', the url is static, I don't know to change it. Also, I hope when I click the edit button the form is filled by the old data before I edit it. Here the part of my templates <body> <h1>List Company Database</h1> <div class="topsection" style=f> <div class="float-end topsectionbutton"> <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#modalAdd" data-backdrop="static" data-keyboard="false" style="cursor:pointer">Add</button> </div> </div> <hr> <table id="tableListCompany" class="table table-bordered" cellspacing="0" width="100%" style="word-break: break-word;"> <thead> <tr> <th scope="col" style="text-align:center" … -
SyntaxError: Unexpected identifier when using Rollup on Github Actions w/ pnPM
I'm building a open source documentation generator.. I am using rollup to bundle all my typescript files. It seems to work perfectly on my pc but when the build process is carried out by a Github Action it returns this Syntax error. My workflow: name: Changesets on: push: branches: - main env: CI: true PNPM_CACHE_FOLDER: .pnpm-store jobs: version: timeout-minutes: 15 runs-on: ubuntu-latest steps: - name: 🛒 Checkout code repository uses: actions/checkout@v3 with: fetch-depth: 0 - name: ⚙️ Setup node.js uses: actions/setup-node@v3 with: node-version: 14 - name: 📦 Install pnpm run: npm i pnpm@latest -g - name: ⚙️ Setup npmrc run: echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}" > .npmrc - name: ⚙️ Setup pnpm config run: pnpm config set store-dir $PNPM_CACHE_FOLDER - name: ⬇️ Install dependencies run: pnpm install --frozen-lockfile - name: 📦 Build packages run: pnpm run build - name: Create and publish versions uses: changesets/action@v1 with: commit: "chore: update versions" title: "chore: update versions" publish: pnpm ci:publish env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} Workflow Logs: https://github.com/gaurishhs/documentum/actions/runs/3931056531/jobs/6721823580#step:8 -
Type hints for the generic utility in the Django
def get_or_create_object(self, model : ?(what will be the type?), data: dict) -> ? (what will be the return type): try: obj, _ = model.objects.get_or_create(**data) except model.MultipleObjectsReturned: obj = model.objects.filter(**data).first() return obj get_or_create_object(ModelName, data) What will be the type hint here - as function will get the Model instances dynamically. -
Sourcemap is likely to be incorrect: a plugin (terser) was used to transform files, but didn't generate a sourcemap for the transformation
I'm trying to upgrade mui, rollup, nodejs and npm but encountered this errorenter image description here tsconfig all packages are in their latest version tried these: Rollup is not generating typescript sourcemap How to get rid of the "@rollup/plugin-typescript: Rollup 'sourcemap' option must be set to generate source maps." warning? rollup-plugin-sourcemaps -
How can I get the incoming value of a property that is calculated from related objects in a model's clean method
I have two models, an Invoice model and a LineItem model. The LineItem model looks like this: class LineItem(models.Model): unit_price: models.DecimalField() quantity: models.IntegerField() @property def lineitem_total(self): return self.unit_price * self.quantity The Invoice model also has a total property, which returns the sum of the total of all of the related line items. Now, when the line items related to an invoice get updated, I need to validate if the total property on the Invoice exceeds a certain maximum value. However the clean() method on the Invoice fires before the related line items get updated, so it still returns the old value. I need the validation to happen on the model itself rather than a form. Is there a way to validate the line items? I've tried putting the validation in the Invoice model's clean() method, however the total property still returns the old value before the line items are updated. I've also tried raising a ValidationError in the Invoice model's save() method, however that returns a 500 error. -
Getting an ID (pk) from model.py in django-forms. Bad performance
I can't get the id through the form. I would like to pass variables to SpotifyData but they cannot be "name" values. I need to pass "id" variables. I also have another problem with ArtistForm. I have 90000 different artists in the Artist model so it takes a very long time to load the page using this form (it has to load all this values into the choicefield list) models.py from django.db import models class Region(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Rank(models.Model): name = models.IntegerField() def __str__(self): return self.name class Chart(models.Model): name = models.CharField(max_length=8) def __str__(self): return self.name class Artist(models.Model): name = models.CharField(max_length=60) def __str__(self): return self.name class Title(models.Model): artist = models.ForeignKey(Artist, on_delete=models.CASCADE) name = models.CharField(max_length=60) def __str__(self): return f"{self.artist} - {self.name}" class SpotifyData(models.Model): title = models.ForeignKey(Title, on_delete=models.CASCADE) rank = models.ForeignKey(Rank, on_delete=models.CASCADE) date = models.DateField() artist = models.ForeignKey(Artist, on_delete=models.CASCADE) region = models.ForeignKey(Region, on_delete=models.CASCADE) chart = models.ForeignKey(Chart, on_delete=models.CASCADE) streams = models.IntegerField() def __str__(self): return str(self.title) + ", " + str(self.date) + ", " + str(self.artist) \ + ", " + str(self.region) + ", " + str(self.chart) + ", " + str(self.streams) forms.py from django import forms from .models import * from spotify_data.models import (Region, Rank, Chart, Artist, Title, … -
How to show the value of Model Class Field dynamically in Django Rest Framework
I am new to django. I have following models: class MeetingUpdate(models.Model): meeting = models.ForeignKey("Meeting", on_delete=models.CASCADE) employee = models.ForeignKey("Employee", on_delete=models.CASCADE) work_done = models.TextField() class Meeting(models.Model): team = models.ForeignKey("Team", on_delete=models.CASCADE) name = models.CharField(max_length=128, unique=True) created_at = models.DateTimeField() class Team(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField("Employee") class Employee(models.Model): name = models.CharField(max_length=128) This is my viewset: class MeetingUpdateViewSet(ModelViewSet): serializer_class = serializers.MeetingUpdateSerializer queryset = MeetingUpdate.objects.all() When I hit the API, I want to show the values of employee attribute dynamically based on the attribute value of meeting selected inside MeetingUpdate Model class. Employee attribute should display only those employees which are in a particular team,instead of showing all the employees.In my MeetingUpdateModel class, I have an attribute Meeting, which further has attribute team, which will tell about a particular team. We can access members that are in a particular team. How to do it?