Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to constrain foreign key to field in other foreign key?
Sorry for the horrible question title, I'm not sure how to phrase this. Here's a dummy example to make things clear. If I have models like: class Shop(models.Model): mechanics = models.ManyToManyField(mechanic) class Mechanic(models.Model): name = models.CharField() class Car(models.Model): problem = models.CharField() shop = models.ForeignKey(Shop, on_delete=models.SET_NULL, blank=True, null=True) fixer = models.ForeignKey(Mechanic, on_delete=models.SET_NULL, blank=True, null=True) How do I restrict the model so that fixer is always only ever a mechanic in the same shop as the car? Hopefully this is straight forward, but I've been scouring the Django docs and Stackoverflow and things haven't quite come together. I've looked into using a CheckConstraint on the model, but I'm not sure how to format the query. I've also learned about the limit_choices_to of a ForeignKey, but have run into a similar problem. Any help is appreciated. Thank you! -
how can i show many-to-mant-field objects in a form?
hi i wrote a code to make genre section in site and i used many-to-many-field in models to add it: from django.db import models from django.contrib.auth.models import User class Genre(models.Model): name = models.CharField(unique=True,max_length=20) def __str__(self): return self.name.title() class Mdata(models.Model): name = models.CharField(max_length=100) artist = models.CharField(max_length=150) album = models.CharField(max_length=100) nation = models.CharField(max_length=100) duration = models.DecimalField(max_digits=4,decimal_places=2) released_in = models.DecimalField(max_digits=4,decimal_places=0) uploaded_at = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='images/',blank=True,null=True) audio = models.FileField(upload_to='audios/',null=True,blank=True) genre = models.ManyToManyField(Genre) uploader = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.name.title()+" by "+self.artist.title() but when i check music itself in site it just show how many object I've selected not genre's as you can see here: [![screen shot][1]: https://i.stack.imgur.com/xHaMK.png here's my template: {% extends 'pages/base.html' %} {% block content %} <form> {% if mdata.image %} <img src="mdata.image.url" height="500" width="500"> {% endif %} {% for field in form %} <p>{{ field.label }} : {{ field.value}}</p> {% endfor %} </form> <a href="{% url 'pages:edit_music' mdata.id %}">edit</a> {% endblock %} and forms(forms is simple i just added models as field): from django import forms from django.forms import ModelForm from .models import Mdata class MdataForm(ModelForm): class Meta: model = Mdata fields =[ 'name', 'artist', 'album', 'genre', 'nation', 'duration', 'released_in', 'image', 'audio', ] -
How to sorting with attrgetter from common foreign key attribute
doc_skai = DocSKAI.objects.all() doc_added = DocAddedSKAI.objects.all() result_list = sorted(chain(doc_skai, doc_added),key=attrgetter('???'), reverse=True) both doc_skai and doc_added have foreign key with model Document, and Document model have a field of 'published_date'. How can I sort the result list from the published_date of Document? -
How to get a list of field names of a queryset in Django
I have a queryset whose fields are being selected with a multiple choice filter. So I wonder how can I get a list of field names of a query of this set. Person.objects.all() : <QuerySet [{'id': 1, 'name': 'Josh', 'surname': 'Smith', 'age': 28, 'address': 'New York'}]> What I'm trying to get : ['name', 'surname', 'age', 'address'] -
How do I fix an error when sending an email in django?
I have a PasswordReset setup in django for when I forget my password, but when I test it, I get this error. [WinError 10061] Could not connect because the target computer refused. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'localhost' EMAIL_PORT = 25 EMAIL_HOST_USER = 'apptest' EMAIL_HOST_PASSWORD = 'xxxxxxxx' EMAIL_USE_TLS = False -
File uploaded in my form is not showing up in my edit/update form
When I fill out my form with its file, it apparently submits, but when checking it out when editing/uploading, all data in the form shows up except my file. So, I cannot access it at all. I guess it probably has something to do with my views.py (the function is for both, save a form for the first time and visualizing them), so here it goes #views.py def contract_form(request, id=0): if request.method == "GET": if id == 0: form = ContractsForm(request.FILES) else: contratos = Contratos.objects.get(pk=id) form = ContractsForm( instance=contratos) return render(request,"contracts_form.html", {'form':form}) else: if id == 0: form = ContractsForm(request.POST, request.FILES) else: contratos = Contratos.objects.get(pk=id) form = ContractsForm(request.POST, request.FILES, instance= contratos, ) if form.is_valid(): form.save() messages.success(request, "Form submission successful") else: messages.error(request, "Error, contract not submitted") return redirect('/contracts') Just in case, every other instance that has something to do with the upload file: #models.py attached_file=models.FileField(upload_to="media", blank=True) My form is stated with <form enctype="multipart/form-data" action="" method="post" autocomplete="off" class="row g-3"> #contracts_form.html <label for="{{ form.subject.id_for_label }}">Attached File:</label> {{form.attached_file}} {% if Contracts.media %} <a href="{{Contracts.media.url}}"></a> {% endif %} #settings.py MEDIA_ROOT=os.path.join(BASE_DIR, 'uploads/') MEDIA_URL="/contracts-media/" path('contracts/edit/<int:id>', views.contract_form, name='edit'), #edit/update form path('contracts/add', views.contract_form, name = 'new-contract'), #add a contract ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ```` -
Changing TailwindCSS class using Django and JS
I have the following code: <nav class="mt-4 flex flex-1 flex-col space-y-2 bg-gray-300 space-y-auto" aria-label="Transporters"> {% if list_transporters_results|length > 0 %} {% for item in list_transporters_results %} <div> <div class="flex flex-row items-center justify-between p-2" id="container-button-transporter-{{ forloop.counter }}"> <button type="button" hx-get="{% url 'tool:results-transporter' slug=item.slug pk=item.pk %}" hx-target="#stats" hx-swap="innerHTML" hx-trigger="click" class="cursor-pointer" id="button-transporter-{{ forloop.counter }}" onclick="get_id_transporter(this.id)" >{{ item.transporter }}</button> <div class="bg-[#195266] rounded-full p-2 self-center mr-2"> <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"> <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/> </svg> </div> </div> </div> {% endfor %} {% else %} <div> <div class="flex flex-row items-center justify-between"> <p class="text-center">No transporters yet.</p> </div> </div> {% endif %} </nav> My objective is to change the class of the div id="container-button-transporter-{{ forloop.counter }}" by clicking on the button button-transporter-{{ forloop.counter }}. Using forloop.counter, I have div such as: container-button-transporter-1 container-button-transporter-2 etc. To update the Tailwind class, I have the following JS script: <script> var transporterId; var numberTransporter; function get_id_transporter(clickedId){ transporterId = clickedId; numberTransporter = parseInt(transporterId.split("-")[2]); } const button = document.getElementById(`button-transporter-${numberTransporter}`); if(button){ button.addEventListener('click', function handleClick() { document.getElementById(`container-button-transporter-${numberTransporter}`).className = "flex flex-row items-center justify-between p-2 bg-[#195266]"; document.getElementById(`button-transporter-${numberTransporter}`).className = "text-white"; }); } </script> The code above does not work with the variable numberTransporter. However, if I change to … -
usage of django context variable as html tag attribute
I'm trying to understand how context variables work in templates. Is it mandatory to use quotations around the context variable. for example if my code is as follows view: def view(req): return render(req, 'index.html', {'class': 'style'} html: <h1 class="{{class}}">hello world</h1> i saw the above usage in several places. here my doubt is since it's a string variable, can it be used without quotations like? <h1 class={{class}}>Hello World</h1> Or is there any reason to use those quotations? because those two are working same. am i missing anything? -
Como descargar una imagen/pdf Django templates
Como puedo descargar una imagen o pdf desde mis templates en Django? al momento de hacer la descarga del pdf este se abre en otra pestaña e igualmente cuando intento descargar una imagen.¨ models.py from django.utils import timezone from django.db import models from django.core.validators import FileExtensionValidator import uuid # Create your models here. class Imagenes(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) image = models.FileField(verbose_name='Imagenes' ,upload_to='imagenes', validators=[FileExtensionValidator(allowed_extensions=['jpg', 'jpeg', 'png'])]) fecha_subida = models.DateTimeField(default=timezone.now) class Meta: verbose_name = "Imagenes" views.py def imagelinks(request, id): imagen = get_object_or_404(models.Imagenes, id=id) descarga = models.Imagenes.objects.filter(id=id) data = {"formu":UploadImageForm(instance=imagen), 'descargas':descarga} return render(request, 'imagenes/linkimagenes.html', data) urls.py from django.urls import path from imagenes import views urlpatterns = [ path('downloadi/<id>/', views.imagelinks, name="imagenlinks"), path('imagenes/', views.SubirImage, name="imagenes") ] template {% extends 'base/base.html' %} {% block title %} {% endblock %} {% block header %} <h3 class="float-md-start mb-0"><a href="{% url 'home' %}">Archinon</a></h3> <nav class="nav nav-masthead justify-content-center float-md-end"> <a class="nav-link fw-bold py-1 px-0" href="{% url 'archivos' %}">Archivos</a> <a class="nav-link fw-bold py-1 px-0" href="{% url 'imagenes' %}">Imagenes</a> <a class="nav-link fw-bold py-1 px-0" href="{% url 'videos' %}">Videos</a> </nav> {% endblock %} {% block content %} <main class="px-10"> <h2>¡Descarga tu Imagen! </h2> {% load archivo_tags %} {% for file in descargas %} <a>{{file.image}}</a> <a href="{{ file.image.url }}" class="btn btn-primary btn-sm" … -
Fixing a typo in models.py and migration for django python project
I'm working on my first django project following along with a youtube tutorial. In models.py while following along I made a typo... crated_at = models.DateTimeField(default=datetime.now) "crated_at" should be "created_at". The typo is reflected in my migrations. I tried changing both models.py and the migrations py file but it leads to an error so I changed it back to "crated". I think the problem is that the database saves the information as "crated_at". I don't want to delete the migration and redo the migrations because from what I read the database is already labeled and it won't fix the problem. Also, I don't mind if it's left as "crated_at" in models.py and the migrations, but at least I would like it to see "created at" when I'm signed in as admin. I want to move on but when I sign in as admin "crated at" is staring me in the face. I feel like this is a good learning moment. Thank you. -
Python DJango avoid assigning variables
def myview(request): category="" brand="" series = "" model="" resolution="" ram="" #some process return render(request ,'mypage.html',{'category':category,'brand':brand,'series':series 'model':model,'resolution':resolution,'ram':ram} Sometimes in my Django projects I have to assign these variables first in my views because of the returning template tags. But doing this way is kinda ugly. Can I avoid assigning these variables in my views? -
Django - Storing user-defined querying logic in a model
I'm making a school app with DRF. Teachers are able to create Exercises and associate them with Tags. An Exercise is thus in m2m relationship with Tag: class Exercise(models.Model): MULTIPLE_CHOICE_SINGLE_POSSIBLE = 0 MULTIPLE_CHOICE_MULTIPLE_POSSIBLE = 1 OPEN_ANSWER = 2 JS = 3 C = 4 EXERCISE_TYPES = ( # ... ) DRAFT = 0 PRIVATE = 1 PUBLIC = 2 EXERCISE_STATES = ( # ... ) exercise_type = models.PositiveSmallIntegerField(choices=EXERCISE_TYPES) state = models.PositiveSmallIntegerField(choices=EXERCISE_STATES, default=DRAFT) text = models.TextField(blank=True) tags = models.ManyToManyField(Tag, blank=True) class Tag(models.Model): name = models.TextField() Teachers can use tags to create quizzes that randomly select exercises with certain tags. In order to do this, there's a Rule model, to which one or more Clauses are related. A Clause is in a m2m relationship with Tag. Let's say a Rule has two Clauses associated; the first clause is associated to tag t1 and t2, and the second clause is associated to t3 and t4. The Rule logic will pick an exercise that has these tags: (t1 OR t2) AND (t3 or t4) class EventTemplateRule(models.Model): pass class EventTemplateRuleClause(models.Model): rule = models.ForeignKey( EventTemplateRule, related_name="clauses", on_delete=models.CASCADE, ) tags = models.ManyToManyField(Tag, blank=True) The actual query is constructed at runtime using repated filter applications and Q objects. … -
Django django-otp non-admin
The following is an excellent article to implement django-otp for admin pages. I tried and it works like a charm. Adding the following two lines in project urls.py seems to do the trick for admin pages: from django_otp.admin import OTPAdminSite admin.site.__class__ = OTPAdminSite OTP for admin I am using django-volt-dashboard. What changes are needed for a similar functionality to access non-admin pages with a regular user? -
Filter object and order by number of filters matched
I have the objects >>> Post.objects.create(name='First post', tags=['tutorial', 'django', 'example']) >>> Post.objects.create(name='Second post', tags=['thoughts']) >>> Post.objects.create(name='Third post', tags=['thoughts', 'django', 'example']) I want to filter the Post objects to match a series of tags: >>> filtered = Post.objects.filter(tags__in=['thoughts', 'django', 'example']) Is there a way to order these results by the number of filters they matched? Wanted result: >>> filtered[0] <Post: Third post> >>> filtered[1] <Post: First post> >>> filtered[2] <Post: Second post> Actual result: >>> filtered[0] <Post: First post> >>> filtered[1] <Post: Second post> >>> filtered[2] <Post: Third post> I'm using Django 3.2.14 -
Django ORM query on fk set
I have a problem with lookup that looks for a value in related set. class Room(models.Model): name = models.Charfield(max_lentgh=64) class Availability(models.Model): date = models.DateField() closed = models.BooleanField(default=False) room = models.ForeignKey(Room) Considering that there is one availability for every date in a year. How can use ORM query to find whether room withing given daterange (i.e. 7 days) has: availability exist for every day within given daterange none of the availabilities has closed=True I was unable to find any orm examples that check whether all objects within daterange exist -
Reverse for 'profileEditor' with no arguments not found. 1 pattern(s) tried: ['regisApp/(?P<pk>[0-9]+)/profileEditor/\\Z']
Hello every one like a lot of people I'm having this ( Reverse for 'profileEditor' with no arguments not found. 1 pattern(s) tried: ['regisApp/(?P[0-9]+)/profileEditor/\Z'] ) I've been trying some of the solution given to other people but with no luck. This is what I'm trying to pass in my home.html menu, is a page were the user can edit their profile <li><a href="{% url 'profileEditor' %}">Edit Profile</a></li> in my url.py I have this path path('<int:pk>/profile_Editor/', editProfilePage.as_view(), name="profileEditor"), And this is my views.py class class editProfilePage(generic.UpdateView): model = Profile template_name = "registration/profileEditor.html" fields = [ 'bio', 'profile_pic', 'website_url', 'facebook_url', 'instagram_url', 'github_url' ] success_url = reverse_lazy('home') I don't get it cuz I did the same process for some of the other pages and they are working fine -
Is there a way to get a function from a user in python with different python functions(ie. if with personalized format)
I'm making a django model that takes a string from the user and that string would be something like '(some var)+15+IF((condition),(passed),(not passed))' and I want it to solve all of this and probably add other personalized functions in the future so mainly for the if this would initially not work with eval from what I looked at. -
Is there a way to create an on_delete function that uses info from the specific model that holds a foreign key in django?
I'm doing one of the problems in the cs50 web course and I made a model for a listing on an auction site. For the sake of avoiding iterating through all bids on a listing, each listing has a Foreign Key called 'current_bid' that points to the latest bid. If the bid were to be deleted though, I want to be able to set the current bid to be the bid that came before it. I've tried several approaches but the one that felt closest to working was making a function local to the model class that gets the lastest bid and tried to make it work by having on_delete call set(last_bid). def last_bid(self): bids = self.bids last = None for bid in bids: if last is None: last = bid elif bid > last: last = bid return last current_bid = models.ForeignKey('Bid', null=True, blank=True, on_delete=SET(last_bid), related_name="running_bids") It doesn't work because calling last_bid this way doesn't give it the needed 'self' parameter. Is there really no way for me to get a reference to the specific listing when the bid it's holding gets deleted? -
How to fix PostgreSQL encode
I am trying to migrate a database from a local computer(Windows, SQLite3) to a server(Ubuntu 20, PostgreSQL). I created a JSON dump from local SQLite3 base. python manage.py dumpdata > dump.json On the server, I enter into the shell and executed the commands from django.contrib.contenttypes.models import ContentType ContentType.objects.all().delete() quit() And when i'm try refill database python manage.py loaddata dump.json The console responds with this UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte I would be very grateful if you could explain to me how to fix the problem. -
scrollHeight yielding inconsistent results
I came with an idea to use top-bottom pagination. My plan was to use hidden class on the bottom paginator element if ListView fits into the user's viewport. Worked fine but accidentally I found out that once per +/- twenty times it just doesn't work. Using console log I noticed that scrollHeight is yielding inconsistent results, viewportHeight on the other hand works like a charm every time. Django template: <!doctype html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Ubuntu:wght@300;400;500;700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="{% static 'styles/elements.css' %}"/> <link rel="stylesheet" href="{% static 'styles/main.css' %}"/> <script defer src="https://unpkg.com/phosphor-icons"></script> <script defer src="{% static 'js/project-list.js' %}"></script> <title>Browse Projects</title> </head> JS file: 'use strict'; const tagFilterForm = document.getElementsByClassName('tag-filter-form')[0]; const paginatorLinks = document.getElementsByClassName('paginator-link'); const paginatorBottom = document.getElementsByClassName('paginator--bottom')[0]; // Prevent from wiping filters during page change: if (tagFilterForm) { for (let i = 0; i < paginatorLinks.length; i++) { paginatorLinks[i].addEventListener('click', function (e) { e.preventDefault() console.log('clicked') const pageNumber = this.dataset.page tagFilterForm.innerHTML += `<input value="${pageNumber}" name="page" hidden>` tagFilterForm.submit() }); } } // Add bottom paginator if doc height > viewport height: const documentHeight = document.documentElement.scrollHeight; const viewportHeight = window.innerHeight; console.log(documentHeight, … -
Django admin panel show ForeignKey data
I'm trying to display more information in a admin panel and can't I have two models with foreign Key I trying show streets list and add to street name City name class Street(models.Model): name = models.CharField(max_length=50, verbose_name='Street') code = models.IntegerField() city = models.ForeignKey('City', on_delete=models.PROTECT, null=True) class Meta: managed = True db_table = 'street' def __str__(self): return self.name + f'({self.city.name})' class City(models.Model): name = models.CharField(max_length=50, verbose_name='City') code = models.IntegerField() class Meta: managed = True db_table = 'city' def __str__(self): return self.name+ f' ({self.code})' -
django.db.utils.OperationalError: could not translate host name "db" to address: Name does not resolve. How to solve this issue?
Can some body help me solve this issue. Why am i getting this error? I have db in .env host and links, network in docker-compose file too. I am not being to figure out where the issue is being raised. Here is my docker-compose file. version: "3.9" volumes: dbdata: networks: django: driver: bridge services: web: build: context: . volumes: - .:/home/django ports: - "8000:8000" command: gunicorn Django.wsgi:application --bind 0.0.0.0:8000 container_name: django_web restart: always env_file: .env depends_on: - db links: - db:db networks: - django db: image: postgres volumes: - dbdata:/var/lib/postgresql environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} ports: - 5430:5432 networks: - django container_name: django_db here is my .env with database settings DB_USER=admin DB_NAME=test DB_PASSWORD=admin DB_HOST=db DB_PORT=5432 DB_SCHEMA=public CONN_MAX_AGE=60 -
AssertionError with assertIn; Django SafeString
I'm looking to understand why a string returned from a template's render_to_string method causes inconsistent testing when testing in a manner using self.assertIn() in the below TestCase. All the strings being checked for pass with the exception of "=question_id_1" and "id=question_id_1". There appears to be an issue adding question_id_1 after the equal sign. What explaination is there for this to fail? https://docs.djangoproject.com/en/3.2/topics/templates/#django.template.loader.render_to_string https://docs.djangoproject.com/en/4.0/ref/utils/#django.utils.safestring.SafeString class SafeString A str subclass that has been specifically marked as “safe” (requires no further escaping) for HTML output purposes. class TestUserQuestionProfileTemplate(TestCase): @classmethod def setUpTestData(cls): tag1 = Tag.objects.create(name="Tag1") tag2 = Tag.objects.create(name="Tag2") user = get_user_model().objects.create_user("ItsNotYou") profile = Profile.objects.create(user=user) cls.question = Question.objects.create( title="Test Question ZZZ", body="Post content detailing the problem about Test Question ZZZ", profile=profile ) cls.question.tags.add(*[tag1, tag2]) cls.template = render_to_string( "authors/questions.html", {"question": cls.question} ) def test_template_profile_questions_listing(self): self.assertIn("=", self.template) <<< pass self.assertIn("id", self.template) <<< pass self.assertIn("question_id_1", self.template) << pass self.assertIn("id=", self.template) <<< pass self.assertIn("=question_id_1", self.template) << fail self.assertIn("id=question_id_1", self.template) << fail The template authors/questions.html is written as: <div id="question_id_{{ question.id }}"> </div> The output of self.template in the test returns: <div id="question_id_1"> </div> As the test is ran, it returns the following assertion errors: self.assertIn("=question_id_1", self.template) AssertionError: '=question_id_1' not found in '\n<div id="question_id_1">\n\n</div>\n' self.assertIn("id=question_id_1", self.template) AssertionError: 'id=question_id_1' not found … -
Simulate CSRF attack in Django
I'm trying to get an understanding of how CSRF tokens work, currently my goal is to create a situation where the CSRF attack is possible. I'm hosting two Django apps locally on different ports. I access one by localhost:8000, the other by 127.0.0.1:5000 -- that ensures cookies are not shared between apps. There's an API view class ModifyDB(APIView): def post(self,request,format=None): if request.user.is_authenticated: return Response({'db modified'}) else: return Response({'you need to be authenticated'}) which shouldn't be accessed by unauthenticated users. The "malicious" site has a button that's supposed to trigger the attack when a user is logged on the target site: const Modify = () => { const onClick = async e => { e.preventDefault(); const instance = axios.create({ withCredentials: true, baseURL: 'http://localhost:8000', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', } }) const res = await instance.post('/api/modifydb'); return res.data } return ( <button class = 'btn' onClick = {onClick}> send request </button> ) } My authentication settings are as follows: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'my_proj.settings.CsrfExemptSessionAuthentication', ], } where CsrfExemptSessionAuthentication is a custom class that disables csrf protection for my educational purposes: class CsrfExemptSessionAuthentication(SessionAuthentication): def enforce_csrf(self, request): return django.middleware.csrf.CsrfViewMiddleware is also disabled. Both CORS_ALLOW_ALL_ORIGINS and CORS_ALLOW_CREDENTIALS are set to true. My first … -
Django prefetch_related nested models
I want to do a 3 lvl prefetch_related but I can't make it work. views.py: queryset = obj.answer.all().prefetch_related(Prefetch('question ', queryset=Question.objects.prefetch_related(Prefetch('orderedquestion', queryset=OrderedQuestion.objects.prefetch_related('select_set'))))) return AnswerSerializer(queryset, many=True).data And on my Serializers.py I call it like that: json['name'] = answer.question.orderedquestion.select_set.get(id=i).name I don't know if this metters but my OrderedQuestion class inherits from Question. How can I fetch select_set on the first query so my serializer stop doing N queries for each object? Thank you so much for the help.