Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set different permission to edit field on django admin list view depending on a value of this field?
How to set different permission to edit field on django admin list view depending on a value of this field (status)? For example if field status is null this field only for current instance stays readonly on django admin list view, class MyModelAdmin (admin.ModelAdmin): list_display = ['id', 'client', 'status'] list_editable = ('status',) -
Function inside class not executed
I've a method inside a class with (CreateView) that i need to be executed, but i think it's not being executed, in fact 'save' do nothing and the table 'Card_id_user' is empty... Is there a way to solve this problem? Here is the code in my views.py class New_card_creation_view(CreateView): title = "AGGIUNGI CARD" model = Card template_name = "new_card.html" fields = ['card_title', 'description', 'expiration_date', 'column'] def create_card_view(self, request): v = New_card_creation_view(request) v.create_card_view(request) if request.method == 'POST': form = CardCreationForm(request.POST or None) if form.is_valid: form = form.save(commit=False) form.save() nCard=Card_id_user(user_id=request.user.id, card_id= form.id) return render(request, 'board.html'), else: form = CardCreationForm() return render(request, 'new_card.html', {'form': form}) else: form = CardCreationForm() return render(request, 'new_card.html', {'form': form}) def get_context_data(self, **kwargs): context = super(New_card_creation_view, self).get_context_data(**kwargs) context.update({'title': self.title}) return context def get_success_url(self): return reverse('board_view', args=(self.object.column.board.id,)) -
Calling own API endpoints in django command
I'd like to call the endpoint of my own app in a django.core.management.base.BaseCommand pretty much like this with rest_framework.test.APIClient: client = APIClient() client.credentials(HTTP_AUTHORIZATION='Token ' + auth_token.key) url = reverse('myurl-viewset') res = client.post(url, data=payload, format='json') The problem I have with APIClient is that it seems to be using its own testing database and so everything I do within my views to modify the db actually doesn't get inserted into the real database. I need to find a way to call my views/endpoints from a django.core.management.base.BaseCommand class handle function. Any idea how I can solve this? Thanks. -
Django - usage of prefetch_related
no matter how many tutorials/documentation i read i still don't quite understand how exactly i'm supposed to be using prefetch_related. My models.py: class ProfileComment(models.Model): author = models.ForeignKey('Profile', on_delete=models.CASCADE, null=True) date_posted = models.DateTimeField(default=timezone.now, editable=False) body = models.CharField(max_length=180, blank=True) ... class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') comments = models.ManyToManyField(ProfileComment, related_name='comments', blank=True) avatar = models.FileField(upload_to=avatar_folder, default='user-avatar/default.png') ... My views.py: profile = Profile.objects.prefetch_related('comments').get(user=request.user) And in template: {% for comment in profile.comments.all %} <div> <p>Author: {{ comment.author.user }}</p><img src="{{ comment.author.avatar.url }}"> <p>Message: {{ comment.body }}</p> <p>Date posted: {{ comment.date_posted }}</p> </div> {% endfor %} However, no matter what i put in prefetch_related, amount of queries just go up by like 5 for every record -
Demonizing app in python and django using systemd
i'm trying to demonize app in python in django using systemd. [Unit] Description=sklep.kaczkoland.pl service After=network.target StartLimitIntervalSec=0 [Service] Type=simple Restart=always RestartSec=1 User=root ExecStart=/root/ivshop/manage.py runserver 0.0.0.0:2135 [Install] WantedBy=multi-user.target When I look into logs I see Nov 29 18:12:02 vps12830 systemd[1]: Stopped sklep.kaczkoland.pl service. Nov 29 18:12:02 vps12830 systemd[1]: Started sklep.kaczkoland.pl service. App also not work. What I'm doing wrong? -
Django model query with Foreign key and get logged in user
Hi I am trying to add "fields" to my django projects that would be calculated based on query.. Basically I have 2 models one is a user which is an extension of Abstract user class CustomUser(AbstractUser): pass and my main model is Project class Project(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(CustomUser, on_delete=models.PROTECT, editable=False) name = models.CharField(max_length=20, editable=False) total = models.DecimalField(max_digits=6, decimal_places=2, editable=False) created = models.DateTimeField(auto_now_add=True, editable=False, null=False, blank=False) this_month = datetime.datetime.now().month allprojectsthismonth = Project.objects.filter(created__month=this_month) def __str__(self): return self.name I create Project objects via a web form using this view: def homepage(request): if request.method == "POST": project = Project() name = request.POST.get('name') total = request.POST.get('total') created = datetime.datetime.now() user = request.user project.user = user project.name = name project.total = total project.created = created project.save() #return HttpResponse(reverse("homepage.views.homepage")) return render(request, 'homepage.html') else: return render(request, 'homepage.html') What I need now is to have a queryset that gets me the combination of the total of a given user Project object so that I can make calculations on it, how would I go about doing that? ideally I would get the logged in user and I could add to my view the sum of all Project.object.total with user = currently logged in. Thanks -
Django Chartjs outputs "No data" when data has value 0
I was trying to plot some Doughnut graphs with Django and chartJS. But stuck at a problem. When the data has value = 0, I want the output in place of doughnut as "No data". I researched for ngIf but the output is not as expected. Here is my code index.html <div class="card-body card-body-cascade text-center"><div class="chartjs-size-monitor" style="position: absolute; left: 0px; top: 0px; right: 0px; bottom: 0px; overflow: hidden; pointer-events: none; visibility: hidden; z-index: -1;"><div class="chartjs-size-monitor-expand" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;"> <div style="position:absolute;width:1000000px;height:1000000px;left:0;top:0"></div></div><div class="chartjs-size-monitor-shrink" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;"> <div style="position:absolute;width:200%;height:200%;left:0; top:0"></div></div></div> <canvas id="doughnutChart" height="250" width="730" class="chartjs-render-monitor" style="display: block; width: 408px; height: 272px;" ng-if="data.length <= 0"></canvas> <span ng-if="data == 0">No data</span> </div> And the JS for doughnut is like this <script> chartIt(); async function chartIt() { const data = await getData(); var ctx = document.getElementById("doughnutChart").getContext('2d'); var myLineChart = new Chart(ctx, { type: 'doughnut', data: { labels: ['d1','d2'], datasets: [{ data: ['0','0'], backgroundColor: ["#F7464A", "#46BFBD", "#FDB45C", "#949FB1", "#4D5360"], hoverBackgroundColor: ["#FF5A5E", "#5AD3D1", "#FFC870", "#A8B3C5", "#616774"] }] }, options: { responsive: true } }); } </script> -
Adding form in a ListView template
So, I built a listview which works fine. I was also able to add the form onto the same page as the listview. However, when I submit the form, the listview does not get updated with the recent form I submitted. I also get a strange error as well. I am not sure what went wrong. views.py class BlogListView(ListView, ModelFormMixin): model = Post context_object_name = 'blog_list' template_name= 'blog/blog_home.html' cats = Category.objects.all() ordering = ['-post_date'] form_class = PostForm def get(self, request, *args, **kwargs): self.object = None self.form = self.get_form(self.form_class) return ListView.get(self, request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = None self.form = self.get_form(self.form_class) if self.form.is_valid(): self.object = self.form.save() return self.get(request, *args, **kwargs) def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(BlogListView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu context["form"] = self.form return context urls.py path('',BlogListView.as_view(),name='blog_home'), forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields =('title', 'category', 'body') widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'category': forms.Select(choices=choice_list,attrs={'class': 'form-control'}), 'body': forms.Textarea(attrs={'class': 'form-control'}), } blog_home.html: <div class="card-body"> <form action="" method="post"> <div class="form-group"> {% csrf_token %} {{ form.media }} {{ form|crispy }} <input type="submit" value="Post"/> </div> </form> </div> Error when form method is "post": IntegrityError at / null value in column "author_id" violates not-null constraint … -
I want to assign a specific customer's grand total into a variable
I want to assign a specific customer's grand total into a variable. I have this Model: class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.IntegerField() date = models.DateField(datetime.datetime.today, null=True) status = models.ForeignKey(Status, on_delete=models.CASCADE, blank=True, null=True) payment_method = models.ForeignKey(PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) total = models.IntegerField(null=True, blank=True) def save(self, *args, **kwargs): self.total = self.price * self.quantity return super().save(self, *args, **kwargs) Here i have a field called total. When a customer place a order its show a total. so here i want to take total_by_customer_id after that i want to assign into a variable then i want to substract with the balance. Here is views: class UserInvoice(View): def map_func(self, product): cart = self.request.session.get('cart', None) product_id = str(product.id) if product_id in cart: return product.price * cart[product_id] def get(self, request, id): user_orders = Order.objects.get(pk=id) args = {'user_orders':user_orders} return render(self.request, 'Home/invoice.html', args) def post(self, request, *args, **kwargs): customer = request.session.get('customer') print(customer) index = Order.get_orders_total_by_customer(customer.total) print(index) balance = request.session['customer']['coin'] print(balance) if balance >= index.total: balance = balance - index.total print(balance) # Customer.objects.filter(id = request.session['customer']['id']).update(coin=balance) customer = Customer.objects.get(id = request.session['customer']['id']) customer.coin = balance customer.save() request.session['customer']['coin'] = balance return … -
Overriding AdminTimeWidget for a different input_type
If i pick up the default TimeInput class i'm able to change the input type of the element rendered in the template, for example: from django import forms class TimeInput(forms.TimeInput): input_type = 'time' If i use this widget, i'll get a <input type="time">. However, if i try to override the AdminTimeWidget, which also descends from TimeInput, the element is rendered as <input type="text">. Example: class AdminTimeWidget(forms.TimeInput): input_type = 'time' class Media: js = [ 'admin/js/calendar.js', 'admin/js/admin/DateTimeShortcuts.js', ] def __init__(self, attrs=None, format=None): attrs = {'class': 'vTimeField', 'size': '8', **(attrs or {})} super().__init__(attrs=attrs, format=format) class CountTimeForm(forms.Form): from_time = forms.TimeField(widget = AdminTimeWidget(), required=False) In here, the from_time input will be rendered as a text input... How can i fix it, in order to render as a time input? -
Error loading psycopg2 module on OS Big Sur i.c.w. Apple Silicon
Try to install a Django Project on my new Apple Silicon machine with OS 11/Big Sur. When I try to run a manage.py command I get the following error: /venv/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 29, in <module> raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: dlopen({removed}/venv/lib/python3.8/site-packages/psycopg2/_psycopg.cpython-38-darwin.so, 2): Symbol not found: _PQbackendPID Referenced from: {removed}/venv/lib/python3.8/site-packages/psycopg2/_psycopg.cpython-38-darwin.so Expected in: flat namespace I have postgres installed with the Postgres.app Tried al kind go things. f.i. setting up the following symlink in /usr/local/lib libpq.5.dylib -> /Applications/Postgres.app/Contents/Versions/latest/lib/libpq.5.13.dylib Installing the psycopg2-binary gave me other errors. So far, no luck. Not sure if the cause is OS11 or the new Silicon. -
Sendgrid API - Adding complete HTML Template (including the headers and styles)
I am not able to figure out how I can send a complete HTML email template to Sendgrid using the v3 API. I need to create templates on Sendgrid on the fly on the basis of user input (the user input determines the CTA link in the template as well as send these email to actual people using personalizations.) But at the same time, I should be able to send an entire HTML (along with Headers and Styles) to Sendgrid for processing these email. Thanks -
Django - How to return only form validation messages rather the form itself?
In a Django learning project, I want to return only the custom validation messages either as a list or tuples. But almost all tutorial I found online are utilizing the Form classes, almost similar to the following code: def save(request): if request.method == "POST": form = RegistrationForm( request.POST ) if form.is_valid(): # save employee return redirect('index') else: form = RegistrationForm() return render(request, 'form.html', {'form': form}) Where RegistrationForm contains the following code: from django import forms class RegistrationForm(forms.Form): first_name = forms.CharField(min_length=4) last_name = forms.CharField(required=False) email = forms.EmailField() contact_no = forms.CharField(min_length=11) gender = forms.CharField(min_length=4) This validation is working, it returns the form with all validation messages. But what I want is: I want to return the validation messages, rather than the form itself. I am pretty new in Django so I can not figure out a suitable way (if there is any) how to return validation messages as a list or tuples rather as the form object. Can anyone help to solve the issue? -
GET Django products and their thumbnails from foreignKey with single query
I have these two Django models: class Product(models.Model): name=models.CharField(max_length=300) description=models.CharField(max_length=10000) class Thumnbnail(models.Model): thumnbnail=models.ImageField(null=True) product=models.ForeignKey(Product, related_name='related_product', on_delete=models.CASCADE) User inputs some keyword, and based on that, I filter the product names, and matching product names are shown, together with all their product's thumbnails. What is the most efficient way to retrieve all the products, and all their thumbnails, without querying twice separately for the products and for the thumbnails? I know that using .select_related() we can fetch the foreign objects as well, but we can make either a) two separate serializers for each model separately, thus requiring to have two separate viewsets, two querysets and two accesses to the database, or b) nested Serializer, with fields from both models, but in that case we will get repeating data, the product_description will appear in every row for every thumbnail, which is also a problem, since that description can be many characters long, and will be an overkill to repeat it. Omitting it from the fields is not an option either, as I do need to get it at least once somehow. Is there a third, more efficient way? I expect this to be possible with accessing the database only once, but I can't … -
django two-step authentication(otp) with allauth
I want to implement two-step authentication with allauth(otp). Already, normal authentication of allauth is implemented with email Please teach me how to implement two-step authentication(otp) with email. -
Django & MeMSQL Error when running migrate.py: django.db.utils.OperationalError: (2012, 'Error in server handshake')
I have a Django application with a default MySQL database. I want to move my default Database to MeMSQL. I set the credentials in settings.py to be: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': MEMSQL_DB, 'USER': MEMSQL_USER, 'PASSWORD': MEMSQL_PASSWORD, 'HOST': MEMSQL_HOST, 'PORT': '3306' } I try to run manage.py migrate to move all models to the new DB, and get this error: django.db.utils.OperationalError: (2012, 'Error in server handshake') If it helps - I tried to test the connection and credentials throughout a workbench (SQL-Pro), and it work successfully. only the manage.py migrate give me this error -
pipenv failed parsing requirement
I'm new to pipenv and installations in Mac Terminal. I was trying to install Django through pipenv and was getting the following error: ''' File "/Users/sidm/Library/Python/2.7/lib/python/site-packages/pipenv/vendor/requirementslib/models/requirements.py", line 969, in _parse_name_from_line "Failed parsing requirement from {0!r}".format(self.line) pipenv.vendor.requirementslib.exceptions.RequirementError: Failed parsing requirement from u'--python3.7' ''' I'd be so grateful if someone helps me resolving this issue. Cheers. -
Django rest authentication error in processing password_reset | dj-rest-auth
In my project, I tried to allow users to change and reset password. But can't figure out why this mail configuration isn't working. Actually, it doesn't send mail to the user. But showing e-mail has been sent on API. Here is my code: settings.py REST_SESSION_LOGIN = True EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' SITE_ID = 1 ACCOUNT_EMAIL_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'username' ACCOUNT_EMAIL_VERIFICATION = 'optional' #mail config EMAIL_HOST = 'smtp.gmail.net' EMAIL_PORT = 587 EMAIL_HOST_USER = 'mygmail@gmail.com' EMAIL_HOST_PASSWORD = '************' #gmail app password EMAIL_USE_TLS = True urls.py urlpatterns = [ path('admin/', admin.site.urls), path('authentication/', include('dj_rest_auth.urls')), path('authentication/registration/', include('dj_rest_auth.registration.urls')), path('api/', include('articles.api.urls')), re_path(r'^authentication/password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view(), name='password_reset_confirm') ] And in terminal at from it shows webmaster@localhost. But why it isn't showing EMAIL_HOST_USER e-mail. Subject: Password reset on example.com From: webmaster@localhost To: gicof53256@tdcryo.com Date: Sun, 29 Nov 2020 08:14:16 -
SQl not connected
I have sql installed but then also its showing me this django.db.utils.OperationalError: (1045, "Access denied for user 'mahima'@'localhost' (using password: YES)") this is from my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dev_jrc_api', 'USER':'mahima', 'PASSWORD':'****', 'HOST':'192.168.0.37', 'PORT':'3307', 'OPTIONS':{'init_command':"SET sql_mode='STRICT_TRANS_TABLES'"} } } -
Reuse Primary Key in another Django model field
Is it possible to reference the primary key in another field in a Django model? For example, let's say I want to have a field looking like BUG0001 corresponding to the entry with pk=1. What is the best way to achieve this? I think it is best to keep the primary key as an integer as it is easier to deal with, and I guess formatting the primary key every time is not very effective. -
Saving into through table m2m
I'm trying to save into a table that i created to handle many2many relation. I didn't know why, but my form save into table 'Card', but doesn't save into 'Card_id_user' and i don't get why. This is my code... class New_card_creation_view(CreateView): title = "AGGIUNGI CARD" model = Card template_name = "new_card.html" fields = ['card_title', 'description', 'expiration_date', 'column'] def create_card_view(request): if request.method == 'POST': form = CardCreationForm(request.POST or None) if form.is_valid: form = form.save(commit=False) """nc = Card_id_column(card_id=form.id, column_id=request.column.id) nc.save()""" n_card = Card_id_user(card_id=form.id, user_id=request.user.id) n_card.save() form.save() return render(request, 'board.html') else: form = CardCreationForm() return render(request, 'new_card.html', {'form': form}) else: form = CardCreationForm() return render(request, 'new_card.html', {'form': form}) def get_context_data(self, **kwargs): context = super(New_card_creation_view, self).get_context_data(**kwargs) context.update({'title': self.title}) return context def get_success_url(self): return reverse('board_view', args=(self.object.column.board.id,)) models.py class Card(models.Model): card_title = models.CharField(max_length=120, verbose_name='Titolo', error_messages={'unique': 'Titolo della Card già utilizzato. Per favore inseriscine un altro.'}) description = models.TextField(default='Il tuo testo...', max_length=300, verbose_name='Descrizione') expiration_date = models.DateTimeField('data di scadenza') column = models.ForeignKey(Column, on_delete=models.CASCADE, verbose_name= 'colonna di riferimento', null=False) story_points = models.PositiveSmallIntegerField(default=0, help_text='inserisci un valore da 1 a 5',validators=[MinValueValidator(1), MaxValueValidator(5)]) id_user = models.ManyToManyField(User, related_name='user_card', verbose_name='id utente', through='Card_id_user') object = models.Manager() class Card_id_user(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) card = models.ForeignKey(Card, on_delete=models.CASCADE) id = models.IntegerField(primary_key=True) n_card seems to be useless -
How to change my inline styles based on the selected language in Django
I am building a django web application. I wish to change the layout of my website from RTL(right to left) to LTR(left to right). I have implemented the HTML[dir='rtl'] in it. It worked but the main issue is that the layout. I want the layouts to get switched from LTR to RTL whenever the selected language is arabic. views.py def index(request): if not request.session.has_key('currency'): request.session['currency'] = settings.DEFAULT_CURRENCY setting = Setting.objects.get(pk=1) # >>>>>>>>>>>>>>>> M U L T I L A N G U G A E >>>>>> START defaultlang = settings.LANGUAGE_CODE[0:2] currentlang = request.LANGUAGE_CODE[0:2] context={'defaultlang': defaultlang} return render(request,'index.html',context) page.html <div id="top-header"> <div class="container"> <div class="{% if defaultlang == 'en' %}pull-left {% else %} pull-right{% endif %}"> <span>{% trans "Welcome to E-shop!" %}</span> </div> <div class="{% if defaultlang == 'en' %}pull-right {% else %} pull-left{% endif %}"> <span>GoodBye</span> </div> </div> </div> I need a way to ensure that the classes change when the language is Arabic. Please kindly help with any suggestions you have.Thanks -
'<=' not supported between instances of 'float' and 'QuerySet'
I want to make a substraction between total (its in model.py) and account balance. So here I have Order Model.py : class Order(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.IntegerField() date = models.DateField(datetime.datetime.today, null=True) status = models.ForeignKey( Status, on_delete=models.CASCADE, blank=True, null=True) payment_method = models.ForeignKey( PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) total = models.IntegerField(null=True) def save(self, *args, **kwargs): self.total = self.quantity * self.price return super().save(self, *args, **kwargs) In this model I have total field so in views.py: def post(self, request, *args, **kwargs): total = Order.objects.filter().only('total') print(total) balance = request.session['customer']['coin'] print(balance) if balance <= total: balance = balance - total print(balance) # Customer.objects.filter(id = request.session['customer']['id']).update(coin=balance) customer = Customer.objects.get( id=request.session['customer']['id']) customer.coin = balance customer.save() request.session['customer']['coin'] = balance return HttpResponse("Remaining balance: " + str(balance)) return HttpResponse("Insufficient Balance") I tried to fetch total field and subtract with balance but its not working and I am getting this error. Another thing is i want to assign total field in a variable after this i want to substract with balance which i showed in views.py Please save me -
How to restrict a custom validator to only pushing errors to field.errors and not django messages?
I am using a custom validator on a model field. Model field: html_content = models.TextField(blank=True, verbose_name=_("HTML content"), validators=[validate_template_syntax]) Validator: def validate_template_syntax(source): try: Template(source) except (TemplateSyntaxError, TemplateDoesNotExist) as err: raise ValidationError(str(err)) However, when the validator error is triggered, it pushes the error to both the django messages framework (messages) and field.errors, so in a template if I am rendering other messages alongside a form the error is displayed twice. How do I restrict the validator to only pushing the error to the field errors context? -
GET products and images from two Django models, by filtering the product name and accessing the database only once
I have two Django models for an eCommerce website: class Product(models.Model): name=models.CharField(max_length=300) description=models.CharField(max_length=10000) class Thumnbnail(models.Model): thumnbnail=models.ImageField(null=True) product=models.ForeignKey(Product, related_name='related_product', on_delete=models.CASCADE) The user will input some keywords, and I filter on the product names with that keyword, and show only those products. With every product, on the results page, I want immediately all its product thumbnails to be loaded and shown as well. How can I retrieve both models in the same viewset and same queryset, in an efficient way? I know I can achieve this with two separate querysets, one being queryset = Product.objects.filter(name__contains="Fanta").all() return queryset and the other viewset for the thumnails queryset = Product.objects.select_related('thumbnail').filter(name__contains="Fanta").all() return queryset # I will create another serializer to only show the thumbnails, for this specific queryset I might not have written the last one most correctly, I am just writing pseudo-code, but I know how to do it. My point is, I need to do the same filtering of the product_names with the input keywords twice, once to retrieve the product names and descriptions, in a ProductViewset, and one more time the same filtering, to get their thumbnails, from a ThumbnailViewset. How do I avoid this, and do the filtering only once? I know …