Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
add form fields's data to existing model fields in Django
I have 2 models, CustomUser and Teacher. Teacher model has a OneToOneFields with CustomUser. models.py class CustomUser(AbstractUser): # some other fields # For Teacher teacher_type = models.CharField(max_length=50, choices=type_choice, blank=True) teacher_department = MultiSelectField(choices=department_choice, blank=True) teacher_year = MultiSelectField(choices=year_choice, blank=True) class Teacher(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) department = models.TextField() year = models.TextField() type = models.CharField(max_length=50) def __str__(self): return '%s %s %s %s' % (self.user.email, self.department, self.year, self.type) forms.py class TeacherRegisterForm(UserCreationForm): class Meta: model = CustomUser fields = ['teacher_type', 'teacher_department', 'teacher_year', ...] def save(self, commit=True): user = super().save(commit=False) user.is_teacher = True user.save() teacher = Teacher.objects.create(user=user) teacher_department_after = ', '.join(self.cleaned_data.get('teacher_department')) print(teacher_department_after) teacher_year_after = ', '.join(self.cleaned_data.get('teacher_year')) teacher.department += teacher_department_after print(teacher.department) teacher.year += teacher_year_after print(teacher.year) teacher.type += self.cleaned_data.get('teacher_type') print(teacher.type) return user When the CustomUser is created, the Teacher object is also created in this line teacher = Teacher.objects.create(user=user) Then, I got the data from CustomUser's fields and get rid of [] and double quotes because teacher_department and teacher_year are MultiSelectField and add these data into department, year, and type inside Teacher model by using += operation. teacher_department_after = ', '.join(self.cleaned_data.get('teacher_department')) teacher_year_after = ', '.join(self.cleaned_data.get('teacher_year')) teacher.department += teacher_department_after print(teacher.department) teacher.year += teacher_year_after print(teacher.year) teacher.type += self.cleaned_data.get('teacher_type') print(teacher.type) When I print out the teacher.department and other 2 fields, … -
Django web service stack and concepts questions
I need to develop a web service with RESTful API on Django. I would be grateful if someone could clarify a few questions and point me in the right direction. It has to connect to a remote database and perform long queries and then return the rows to a user (I plan on returning csv files) I chose Django as a framework, but I am a bit lost with all the things I read Since queries take a long time to finish , the service should somehow work in async. The async concept in regards to web services especially in connection to Django is really complicated to grasp. Would using new Django 3.x async features be enough for this task? I've read about Celery the queue manager that is supposed to provide some degree of parallelisation (am I correct on this?) I've also read about nginx + wsgi + Django. Should I go with that? In regards to nginx and other web servers. Am I correct in understanding that Django in itself can function as a web server, but nginx can be used to somehow better the performance of a Django application? Should I use "django rest framework" for the … -
FieldDoesNotExist at /accounts/signup/, User has no field named 'username'
I am using django allauth, and I am using an AbstractBaseUser, but anytime I click on Sign Up, it says Trace: C:\Users\user1\.virtualenvs\allauthtest-RfdvfJzX\lib\site-packages\django\db\models\options.py, line 577, in get_field raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) FieldDoesNotExist at /accounts/signup/ User has no field named 'username' I have tried this article, but it doesn't seem to help me. In my AbstractBaseUser, i decided to use email, and not username. What should I do? Am I missing some options? models.py class UserManager(BaseUserManager): """ Custom User Model manager. It inherits from BaseUserManager, and has 3 functions, create_user(), create_staffuser(), and create_superuser() It requires email field. """ def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email and password. """ return self._create_user(email, password, False, False, **extra_fields) def create_staffuser(self, email, password, **extra_fields): """ Creates and saves a staff user with the given email and password. """ user=self._create_user(email, password, True, False, **extra_fields) user.save(using=self._db) return user def create_superuser(self, email, password, **extra_fields): """ Creates and saves … -
Other APIs are fetching normal, but some APIs takes time 2-5 minutes to get response, jquery Ajax fetches in milli seconds same APIs
I need to integrate ShipStation with my Python web app. ShipStation APIs are executing very slower by python requests package, taking time about 2-5 minutes. I also tried to fetch more heavier APIs which are fetching normally. I tested Shipstation APIs using jQuery Ajax, Postman and it's taking time in milliseconds, or 1-2seconds. What's wrong with requests library. Please help me. Samples: python example -- taking minutes 2-5 import requests # request header headers = { 'Authorization': '' } # shipstaion carrier services listing api endpoint list_services = 'https://ssapi.shipstation.com/carriers/listservices?carrierCode=stamps_com' # making get request res = requests.get(list_services, headers=headers) # results print("services_list: ", res, " and type is: ", type(res)) jQuery Ajax example taking milliseconds or 1-2 seconds: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> </body> <script> $.ajax({ url: 'https://ssapi.shipstation.com/carriers/listservices?carrierCode=stamps_com', headers: { 'Authorization': '' }, type: "GET", success: function(response) { console.log(response);//does not print in the console } }); </script> </html> -
Two Django Projects with One Database
I built a dashboard with Django that all my customers use. I want to build an internal dashboard for myself so that I can monitor their activity. It should connect to the same database as the dashboard. I have a a question about how to do this: Do I just add the same database in settings.py and re-define the models in the internal dashboard? Thanks! If there's a better way to do this, let me know! -
How to send time to model usinig django-admin commands?
I was wondering how can i send a time to django DateTimeField by a django-admin command class , and by time i mean the actual hour and minute not the date. thanks my django admin command class class Command(BaseCommand): def handle(self, *args, **kwargs): title = 'new new post' try: MyModel.objects.create( title=title, mytime= '???', ) print('%s added' % (title,)) except: print('error') my model class MyModel(models.Model): title = models.CharField(max_length=250) mytime = models.DateTimeField(null=True, blank=True) def __str__(self): return self.title -
How to define a polymorphic relation?
Working on project kinda Reddit, and I am stuck somewhere. I have Post and Group models as in Reddit, and everything works pretty fine, I mean that i can create a post and choose a group, but i want to implement something like in Reddit, when you create a post and you can choose where exactly you will post that(in your profile or in one of your groups). I heard that polymorphism can help with this, and did't find anything useful. Thanks for help My models: class Group(models.Model): title = models.CharField(max_length=100, unique=True) description = models.TextField(max_length=500) class Post(models.Model): title = models.CharField(max_length=150, db_index=True) body = models.TextField(max_length=5000, blank=True, null=True) author = models.ForeignKey(User, related_name='posted_p', on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) -
Reverse for 'createActivity' with no arguments not found. 1 pattern(s) tried: ['create_Activity/(?P<pk>[^/]+)/$']
hope you are doing well! I am having this error Reverse for 'createActivity' with no arguments not found. 1 pattern(s) tried: ['create_Activity/(?P<pk>[^/]+)/$'] it's working for createSousActivity but for createActivity it doesn't work. this is my urls.py path('create_Activity/<str:pk>/', views.createActivity, name="createActivity"), path('update_Activity/<str:pk>/', views.UpdateActivity, name="updateActivity"), path('delete_activity/<str:pk>/',views.DeleteActivity, name="deleteActivity"), path('create_SousActivity/<str:pk>/', views.createSousActivity, name="createSousActivity"), path('update_SousActivity/<str:pk>/', views.UpdateSousActivity, name="updateSousActivity"), path('delete_Sousactivity/<str:pk>/',views.DeleteSousActivity, name="deleteSousActivity"), this is my views.py def createActivity(request,pk): sdlc = SDLC_phase.objects.get(id=pk) form = ActivityForm(initial={'sdlc':sdlc}) if request.method == "POST": form = ActivityForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'form':form} return render(request,'activitiestasks/Activity_form.html', context) in my template <a class="btn btn-outline-success btn-sm btn-block" href="{% url 'createActivity' SDLCphases.id %}">Create Activity</a> do anyone know this problem ? -
Django Background Tasks that execute only after DB table field update
I am using django background tasks package for scheduling my background tasks. I am dividing my tasks into 2 categories say A and B. Assume A have 50 tasks and B have 30 tasks. Initially, all 50 tasks of A should run asynchronously and have to complete. Once completed, those tasks update the db table field. Now B tasks should read the db table field values. If all A tasks marked completed, then B has to trigger asynchronously. Help me on how to achieve this. -
How to inherit 2 admin classes in one admin class Django?
How to inherit 2 admin classes in one model admin? This code works from modeltranslation.admin import TranslationAdmin from .models import Insurance class InsuranceCompanyAdmin(TranslationAdmin): list_display = ["name"] admin.site.register(Insurance, InsuranceCompanyAdmin) I want to something like this (however it doesn't work). I tried use proxy but it didn't help me. How can I inherit 2 admin classes? from import_export import resources from import_export.admin import ImportExportModelAdmin from modeltranslation.admin import TranslationAdmin from .models import Insurance class InsuranceSource(resources.ModelResource): """Ingredient Resource class for importing and exporting.""" class Meta: """Meta class""" model = Insurance skip_unchanged = True report_skipped = True exclude = ('id',) fields = ('name',) class InsuranceImportAdmin(ImportExportModelAdmin): """Ingredient import-export Admin interface""" resource_class = InsuranceSource list_display = ["name"] class InsuranceCompanyAdmin(TranslationAdmin): list_display = ["name"] admin.site.register(Insurance, InsuranceCompanyAdmin) admin.site.register(Insurance, InsuranceImportAdmin) -
Django Queryset filter equivalency to SQL
To me, it is not clear or lack of example code to understand the documentation about how SQL language is internally used in Django ORM. My intended SQL is: SELECT projects_category.id, projects_category.name, projects_project.name FROM projects_category JOIN projects_project_categories ON projects_category.id = projects_project_categories.project_id JOIN projects_project ON projects_project_categories.project_id=projects_project.id WHERE NOT projects_project.is_mini ORDER BY projects_category.id; How to do the same in Django ORM or in Django view? I have tried filter and exclude (probably with the wrong arguments...) and it does not seem working according to output. There might be more options besides these two. Also, any other tricks would be appreciable. -
Custom nested routes django
I have a model class ExampleModel(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4) image = models.ImageField(upload_to='photos') title = models.CharField(max_length=30) kind = models.CharField(max_length=30) size = models.CharField(max_length=30) created_at = models.DateTimeField(auto_now_add=True) my view class Example(viewsets.ModelViewSet): serializer_class = ExampleSerialzer queryset = Example.objects.all() my serializer class ExampleSerialzer(serializers.ModelSerializer): class Meta: model = Example fields = '__all__' Now in my urls.py file I want to be able to do something like router = NestedDefaultRouter() example_router = router.register('example', views.ExampleView) example_router.register('category', views.ExampleView, basename='example_category' lookups=['kind', 'size']) urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), ] My idea with this is that I would be able to go to a route like /api/example/category/:kind/:size/ where the kind and size gets specified by clicking a photo or something of that nature which is not important. Basically, I want to filter from my model by kind and size field but my code does not work -
Understanding Django JSONField key-path queries and exhaustive sets
While looking at the Django docs on querying JSONField I noticed a note stating: Due to the way in which key-path queries work, exclude() and filter() are not guaranteed to produce exhaustive sets. If you want to include objects that do not have the path, add the isnull lookup. Can someone give me an example of a query that would not produce an exhaustive set? I'm having a pretty hard time coming up with one. -
EmailMultiAlternatives works fine on localhost but gives SMTPAuthenticationError on production
i already turned on Less secure app access on my google account settings I checked similar questions but nothing solves my problem i don't know why its working fine on my local host but when i upload my website to pythonanywhere i get this issue i think there's some security protocols that blocks the login process if the website is logging my email account from a different ip address i also want to let you guys know that this same process used to work fine in the last week here is my settings.py #=======email service======== EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'epaydz.cn@gmail.com' EMAIL_HOST_PASSWORD = '************' -
Django Wizard Form : is it possible to have a search engine for a specific step?
I'm struggling with my Django application, to the point of asking my first question on StackOverflow. Te be short, I have a form where the user (a farmer) allow him to add a plant on a culture. It'd be handy if instead of a boring select box, the farmer could just write down a few letters and every related results pop on the screen. The farmer would pick-up the plant, and proceed to the next step. Since he had 330 different seeds, it's not just a fancy functionnality. I'm able to build a "simple" WizardForm, I already have the search engine and my field is populated with a ModelChoiceField()... I feel like I'm soo close yet so far :( I have also considered that WizardForm might not be the right approach for what I'm doing. But I feel like I'm just missing something. Do any of you have any suggestion on it ? Below, you can read a few extract from my code. I will try to clean-up the mess and provide you a readable code. models.py ''' From the model, the only field that interests this question is the second one, id_graine (graine means seed). ''' class Lot(models.Model): id … -
push rejected to heroku
getting this error I have installed all the installation process. Was following this link to push my Heroku app https://www.codementor.io/@jamesezechukwu/how-to-deploy-django-app-on-heroku-dtsee04d4 getting gcc failed with command I have even tried Heroku config: set DISABLE_COLLECTSTATIC=1 but it doesn't help I am doing this for the first time sorry if it's a silly question. C:\Users\great\Desktop\Covid-App\CovidApp>git push heroku master Enumerating objects: 86, done. Counting objects: 100% (86/86), done. Delta compression using up to 8 threads Compressing objects: 100% (81/81), done. Writing objects: 100% (86/86), 35.21 KiB | 1.17 MiB/s, done. Total 86 (delta 13), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.8.5 remote: -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: ! Your Django version is nearing the end of its community support. remote: ! Upgrade to continue to receive security updates and for the best experience with Django. remote: ! For more information, check out https://www.djangoproject.com/download/#supported-versions remote: Collecting dj-database-url==0.4.2 remote: Downloading dj_database_url-0.4.2-py2.py3-none-any.whl (5.6 kB) remote: Collecting Django==1.11.7 remote: Downloading Django-1.11.7-py2.py3-none-any.whl (6.9 MB) remote: Collecting gunicorn==19.7.1 remote: Downloading gunicorn-19.7.1-py2.py3-none-any.whl (111 kB) remote: Collecting psycopg2==2.7.3.2 remote: Downloading … -
Django - CreateView - Send a custom Error Message if model form is not valid
I have some Class Based Views where I use the Django messages framework to send a success_message if the form POST is_valid. I would also like to send a custom error_message if the form POST is not valid. It was very obvious how to configure the success_message, just use the SuccessMessageMixin and add a "success_message" variable. I have tried the same approach for an error_message, but none one of my attempts showed the error flash message on the form page - my attempts are commented out below in the else: block. Sending an error message to a CBV seems like something that would be a pretty common scenario, yet I cannot find any examples in the Django docs or anywhere else online. Does anyone know how I can get this done? Just to be clear - I am not talking about adding ValidationErrors that are created for specific fields. I have ValidationErrors for fields working fine. This refers to a custom flash message that would be present at the top of the page. #views.py class DocCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = Doc form_class = DocForm template_name = "doc/doc_form.html" context_object_name = 'doc' success_message = 'Doc successfully created!' error_meesage = "Error saving the … -
I am trying to implement soft delete in django
I am trying to implement soft delete in django but getting the following error: NoReverseMatch at /admin/trip-issue-report/ Reverse for 'soft-delete-trip-issue' with arguments '(3,)' not found. 1 pattern(s) tried: ['admin/soft\-delete\-trip\-issue/$'] My code: models.py class TripIssue(models.Model): trip = models.ForeignKey(Trip, on_delete=models.CASCADE) issue = models.ForeignKey(Issue, on_delete=models.CASCADE) isSolved = models.BooleanField(blank=False, default=False) is_deleted = models.BooleanField(default=False) deleted_at = models.DateTimeField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def soft_delete(self): self.is_deleted = True self.deleted_at = timezone.now() self.save() views.py class TripIssueSoftDelete(DeleteView): model = TripIssue success_url = reverse_lazy('trip-issue-report') template_name = 'trip_issue.html' def delete(self, request, *args, **kwargs): self.object = self.get_object() self.object.soft_delete() return HttpResponseRedirect(self.get_success_url()) urls.py path('soft-delete-trip-issue/', views.TripIssueSoftDelete, name="soft-delete-trip-issue"), trip_issue.html template {% for trip_issue in trip_issues %} <tr> <td>{{trip_issue.trip}}</td> <td>{{trip_issue.issue}}</td> <td>{{trip_issue.isSolved}}</td> <td>{{trip_issue.updated_at}}</td> <td><a href="{% url 'dashboard:soft-delete-trip-issue' trip_issue.id %}"><i class="fas fa-minus-circle"></i></a></td> </tr> {% endfor %} </tbody> So I need your help to fix the issue and implement soft delete successfully. Thanks in advance. Happy Coding :) -
Identify which password validator rose an error in django form
I have a simple view for signing up which looks like this: class SignUp(CreateView): template_name = 'reg.html' form_class = SignUpForm success_url = 'login' I want to overwrite standard behavior in form_invalid method. I know that there are couple of built in password validators in django. How should I determine which one exactly rose an error? For example if a password was too short I would show different error text. I could simply overwrite the validator itself, but I don't think that it is good approach. -
How to fix this ConnectionError?
[enter image description here][1] [1]: https://i.stack.imgur.com/cDWLr.png I got this problem after implementing elasticsearch This is my installed apps 'corsheaders', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_auth', 'rest_auth.registration', 'rest_framework', 'rest_framework.authtoken', 'oauth2_provider', "elasticsearch_dsl", 'django_elasticsearch_dsl', 'django_elasticsearch_dsl_drf', What can be the problem? -
Unique field value Django model
So, i have two models: RetailStore and Product. Product contains a ForeignKey to RetailStore and a field named sku. Basically what i need is to make sure that the sku field is unique into a store, but not between all stores, e.g: Store1: Product(sku="sku1"), Product(sku="sku2"), Product(sku="sku3"), Product(sku="sku1") <- can't have this last one because it already exists. Store2: Product(sku="sku1"), Product(sku="sku2"), Product(sku="sku3") <- This is ok Store3: [...] <- Same goes for others Store. My Models class RetailStore(StandardModelMixin): cnpj = models.CharField( blank=False, null=False, unique=True, max_length=200, validators=[validate_cnpj], verbose_name="CNPJ" ) [other fields...] class Product(StandardModelMixin, SoftDeletionModel): sku = models.CharField(blank=False, null=False, max_length=200, verbose_name="SKU") [other fields...] retail_store = models.ForeignKey( RetailStore, on_delete=models.CASCADE, blank=True, null=True, related_name="products", verbose_name="Retail Store", ) -
How to access related values with select_related()
I have a QuerySet that I'm attempting to work with the values on related tables. I see the related tables/values when I run the queryset.query, however I'm not sure how to pull those values for use in forms/tables. Here is my QuerySet Object: tpList = AppCustomerTpRel.objects.filter(idcst_rel=selection).select_related('idcst_rel', 'idtrp_rel').values() Here are the related Models. class AppCustomerTpRel(models.Model): id_rel = models.AutoField(primary_key=True) idcst_rel = models.ForeignKey(AppCustomerCst, models.DO_NOTHING, db_column='idcst_rel') idtrp_rel = models.ForeignKey(AppTradingPartnerTrp, models.DO_NOTHING, db_column='idtrp_rel') cust_vendor_rel = models.CharField(max_length=50, blank=True, null=True) sender_id_rel = models.CharField(max_length=50, blank=True, null=True) old_vendor_rel = models.CharField(max_length=50, blank=True, null=True) vendor_name_rel = models.CharField(max_length=50, blank=True, null=True) category_rel = models.CharField(max_length=50, blank=True, null=True) class AppTradingPartnerTrp(models.Model): id_trp = models.AutoField(primary_key=True) tpid_trp = models.CharField(max_length=50, blank=True, null=True) name_trp = models.CharField(max_length=50) description_trp = models.CharField(max_length=100, blank=True, null=True) idtrn_trp = models.ForeignKey('AppTransmissionTrn', models.DO_NOTHING, db_column='idtrn_trp', blank=True, null=True) class AppCustomerCst(models.Model): id_cst = models.AutoField(primary_key=True) is_active_cst = models.BooleanField() name_cst = models.CharField(max_length=50, blank=True, null=True) address_1_cst = models.CharField(max_length=50, blank=True, null=True) address_2_cst = models.CharField(max_length=50, blank=True, null=True) address_3_cst = models.CharField(max_length=50, blank=True, null=True) city_cst = models.CharField(max_length=50, blank=True, null=True) state_cst = models.CharField(max_length=50, blank=True, null=True) zip_cst = models.CharField(max_length=10, blank=True, null=True) country_cst = models.CharField(max_length=50, blank=True, null=True) salesrep_cst = models.CharField(max_length=50, blank=True, null=True) type_cst = models.CharField(max_length=10, blank=True, null=True) is_allowed_flat_cst = models.BooleanField() iddef_cst = models.IntegerField() date_created_cst = models.DateTimeField() date_suspended_cst = models.DateTimeField(blank=True, null=True) date_first_tran_cst = models.DateTimeField(blank=True, null=True) date_last_tran_cst = models.DateTimeField(blank=True, null=True) is_credit_hold_cst = models.BooleanField() old_balance_cst … -
Queryset got bigger after exclusion
This is my shell copy In [18]: Category.objects.all() Out[18]: <QuerySet [<Category: cate uno>, <Category: cate dos>, <Category: cate tres>, <Category: cate cuatro>, <Category: cate cinco>, <Category: cate seis>, <Category: cate siete>, <Category: cate ocho>, <Category: cate ocho>, <Category: cate nueve>, <Category: cate diez>]> In [19]: catesFat = Category.objects.filter(project__isnull = False) In [20]: catesFat Out[20]: <QuerySet [<Category: cate uno>, <Category: cate tres>, <Category: cate cuatro>, <Category: cate uno>, <Category: cate diez>, <Category: cate seis>, <Category: cate dos>, <Category: cate uno>, <Category: cate seis>, <Category: cate siete>, <Category: cate ocho>, <Category: cate dos>, <Category: cate cinco>]> In [21]: It seems fine when I use it in template, but why does it show the redundant queries so it got bigger in shell? -
How to override clean() method for choices in model and field validation?
I want to make check in admin, when I create new equipment I can't save it because wanna raise error. examples: is_active=True First-choice -can is_active=True Second-choice -can is_active=False First-choise - can is_active=True First-choise - ValidationError It must show error others fields also if will have ValidationError is_active=True with already selected choises raise error. Enum choices class EquipmentPage(Enum): FIRST = "First" SECOND = "Second" class Equipment(models.Model): ... page = models.CharField(max_length=7, choices=[(tag.name, tag.value) for tag in EquipmentPage]) is_active = models.BooleanField(default=False) ... Here my not working as expected clean() method def clean(self): if EquipmentPage.FIRST and self.is_active: raise ValidationError(_('Only one equipment can be used')) -
How to filter a reverse related field without additional queries?
How can I filter the reverse relation queryset generated by a ModelViewSet without causing an additional n queries? MRE: models.py: class Product(models.Model): name = models.CharField(max_length=45) image_url = models.URLField() class Item(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.IntegerField() views.py: class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.prefetch_related('items').all() serializer_class = ProductSerializer filter_backends = [filters.DjangoFilterBackend] filter_class = ProductFilter serializers.py: class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__' class ProductSerializer(serializers.ModelSerializer): items = ItemSerializer(many=True, read_only=True) class Meta: model = Product fields = '__all__' filters.py: import django_filters as filters class ProductFilter(filters.FilterSet): price = filters.RangeFilter(field_name='items__price') quantity = filters.RangeFilter(field_name='items__quantity') class Meta: model = Product fields = { 'name': ['icontains'], } Filtering on the Product model's fields works fine, but the items reverse relation ignores the filtering completely. I found a "solution" from this answer; ie. do the filtering via a SerializerMethodField: item_fieldset = {'price', 'quantity'} class ProductSerializer(serializers.ModelSerializer): items = serializers.SerializerMethodField('get_items') class Meta: model = Product fields = '__all__' def get_items(self, product): params = self.context['request'].query_params filter_fields = item_fieldset.intersection(set(params)) filters = {field: params.get(field) for field in filter_fields} serializer = ItemSerializer(instance=product.items.filter(**filters), many=True) return serializer.data But this cripples the performance of my app. Is there a better way?