Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python manage.py runserver b
Sir, I have been trying to run the django server since 1 week but it is showing the same error and i can't understand the error please help me out through this. I have created the virtual environment also and in that i open the folder containing manage.py even though I can't understand the error 🥲. Python version=3.10.6 Django=4.1enter image description here enter image description here -
ModuleNotFoundError: No module named ‘msilib’
After I deployed my Django project in Heroku for the first time and clicked view, I got this error. when I looked up this module it says it is depreciated. I tried pycopy-msilib but it is asking for setup.py which I can’t find how it’s made Any advice or directions would be appreciated. Thank You -
How to get results from database as I wrote in html form?
In my html form Input any text here Here is me Then I store these text into database When I query that text to display html page That show like this: Here is me How can I display these text as what I was wrote in html form ? Note: I use Django framework (python) -
Confirmation modal for deleting an object is not appearing upon clicking the delete button in django
I am using the following library: https://pypi.org/project/django-bootstrap-modal-forms/ but my problem is that when I click on the "delete" icon in the table nothing happens. I have provided snippets of code below urls.py urlpatterns = [ #path('', include(router.urls)), path('', views.index, name='index'), #path('hosts', views.hosts, name='hosts'), path('hosts', HostsView.as_view(), name='hosts'), path('host/new', HostDefinitionView.as_view(), name='new_hostdef'), path('hosts/delete/<int:pk>/', HostDeleteView.as_view(), name='delete_hostdef')] views.py class HostsView(View): model = AvailableHosts template_name = 'generate_keys/hosts.html' def get(self, request, *args, **kwargs): hostdef_objs = AvailableHosts.objects.filter(host_developer_email = request.user.email) host_definition_table = HostDefinitionTable(hostdef_objs) return render(request, self.template_name, {'host_definition_table': host_definition_table}) class HostDeleteView(BSModalDeleteView): model = AvailableHosts success_url = "/hosts" # this shouldn't be hard coded i don't think template_name = 'generate_keys/hosts_confirm_delete.html' success_message = 'success' tables.py class HostDefinitionTable(tables.Table): host_label = tables.Column(verbose_name="Host") host_activation_request = tables.Column() hostdef_status = tables.Column('Operations') class Meta: model = AvailableHosts fields = ("host_label", "host_activation_request", "hostdef_status") template_name = "django_tables2/bootstrap4.html" def render_hostdef_status(self, value, record): tooltip = 'Delete host definition' icon = 'fa fa-eraser' return format_html( '<button type="button" name="delete_hostdef" id="id_delete_hostdef" ' + 'class="btn btn-link btn-delete-hostdef" title="{}"' + #'data-form-url="{% url "delete_hostdef" {} %}" ' + 'data-form-url="{}" ' + '>' + '<i class="{}"></i></button>', tooltip, reverse("delete_hostdef", args=(record.pk,)), icon ) in hosts.html: <script> $(document).ready(function(){ console.log("document is ready") $("#id_create_hostdef_button").modalForm({ formURL: "{% url 'new_hostdef' %}", modalID: "#add-hostdef-modal" }); function deleteHostModalForm() { $(".btn-delete-hostdef").each(function() { $(this).modalForm({ formURL: $(this).data('form-url'), isDeleteForm: true }) }) … -
django convert raw sql query to django orm
i am using django rest framework and i want to do this query in sql but i want to do it in the django orm. I have tried using the different django tools but so far it has not given me the expected result. select tt.id, tt.team_id, tt.team_role_id, tt.user_id from task_teammember tt inner join task_projectteam tp on tp.team_id = tt.team_id where tp.project_id = 1 -
How to make easy to share offline django projects
I have completed a Django project. It runs well on the development server on my machine. However, it can't be shared and run on other devices easily. How can I package it so that it can easily be shared and run on local server, offline on individual machines? What I do: I use xampp to serve it from Apache then manually copy the necessary files. However this has too many setting up steps, copy paste files and not user friendly at all. Is there a better way? -
django.db.utils.DatabaseError with MongoDB as Backend Database
i was using MongoDB as my Backend Database which was working perfectly today until now!. i didn't make any changes, yet suddenly every time i runserver, i get this error. can't even debug what's the issue here. i really haven't made any change in Django yet this is happening. please help me figure this out! #my models.py from django.db import models from django.contrib.auth.models import User class Room(models.Model): name = models.CharField(max_length=100,unique=True,blank=True,null=True) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,default=User.objects.get(id=1).id) rooms = models.ManyToManyField(Room) def __str__(self): return self.user.username class Message(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,blank=False,null=True) message = models.TextField(max_length=500,blank=False,null=True) name = models.CharField(max_length=100,blank=True,null=True) room = models.ForeignKey(Room,on_delete=models.CASCADE,null=True) time = models.DateTimeField(auto_now_add=True) received = models.BooleanField(default=False,null=True) terminal response Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Meraz\anaconda3\lib\site-packages\djongo\sql2mongo\query.py", line 808, in __iter__ yield from iter(self._query) File "C:\Users\Meraz\anaconda3\lib\site-packages\djongo\sql2mongo\query.py", line 166, in __iter__ for doc in cursor: File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\cursor.py", line 1238, in next if len(self.__data) or self._refresh(): File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\cursor.py", line 1130, in _refresh self.__session = self.__collection.database.client._ensure_session() File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\mongo_client.py", line 1935, in _ensure_session return self.__start_session(True, causal_consistency=False) File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\mongo_client.py", line 1883, in __start_session server_session = self._get_server_session() File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\mongo_client.py", line 1921, in _get_server_session return self._topology.get_server_session() File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\topology.py", line 520, in get_server_session session_timeout = self._check_session_support() File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\topology.py", line 504, in _check_session_support self._select_servers_loop( File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\topology.py", line … -
corsheaders.E013 error in django cors headers
I try to open port for using django backend as API at 'http://localhost:3000' here is my implement CORS_ALLOWED_ORIGINS = ( 'http://localhost:3000' ) INSTALLED_APPS = [ * 'corsheaders', ] MIDDLEWARE = [ * "corsheaders.middleware.CorsMiddleware",# new "django.middleware.common.CommonMiddleware", # new * ] but I keep getting the error message like this django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (corsheaders.E013) Origin '/' in CORS_ALLOWED_ORIGINS is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '/' in CORS_ALLOWED_ORIGINS is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '0' in CORS_ALLOWED_ORIGINS is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '0' in CORS_ALLOWED_ORIGINS is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). . . . . . . System check identified 21 issues (0 silenced). PS. python version 3.10.6 django version 4.0.6 django-cors-headers version 3.13.0 -
Django 4.1 can't connect to MSSQL
I have two servers, both running Ubuntu 22.04. The application server is running Django 4.1, and the database server is running a fresh install of SQL Server installed following these instructions. I followed these instructions in order to install the ODBC driver. And then per THESE instructions, set up my Django setttings.py file as follows: default_db_settings = { 'ENGINE': 'mssql', 'NAME': '***', 'USER': '***', 'PASSWORD':'***', 'HOST':'***', 'PORT':'5432', 'OPTIONS':{'driver':'ODBC Driver 18 for SQL Server'} } Trying to visit my site, I get: django.core.exceptions.ImproperlyConfigured: 'mssql' isn't an available database backend or couldn't be imported. just for some sanity checking: sudo apt-get install msodbcsql18 [sudo] password for ***: Reading package lists... Done Building dependency tree... Done Reading state information... Done msodbcsql18 is already the newest version (18.1.1.1-1). 0 upgraded, 0 newly installed, 0 to remove and 18 not upgraded. sudo apt-get install mssql-tools18 Reading package lists... Done Building dependency tree... Done Reading state information... Done mssql-tools18 is already the newest version (18.1.1.1-1). 0 upgraded, 0 newly installed, 0 to remove and 18 not upgraded. sudo apt-get install unixodbc-dev Reading package lists... Done Building dependency tree... Done Reading state information... Done unixodbc-dev is already the newest version (2.3.9-5). 0 upgraded, 0 newly installed, 0 … -
OSError at /register/
OSError at /register/ cannot write mode RGBA as JPEG cant get rid of this error. tried to find solution on stackoverflow cant seem to get one models.py from django.db import models from django.contrib.auth.models import User from PIL import Image # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default = "default.jpg", upload_to = "profile_pics") def __str__(self): return f"{self.user.username} Profile " def save(self, *args, **kwargs): #helps to resize the image super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width >300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) def save_profile(sender, instance, **kwargs): instance.profile.save() -
How to lazy load javascript libraries after a htmx request?
Im creating a webapp dashboard (django + htmx) and I want to only load the plugins that the user needs and not load every single plugin immediately because it would slow down the site. Example: User clicks a button and the whole html body gets replaced with a wysiwyg editor. Whats the best way to dynamically load a JS library after an htmx request? Thanks in advance -
How to add fields from other (non-page) models in Wagtail Page admin?
I am looking for a way to include other model's fields in the Page editor of Wagtail. The scenario is a digital marketplace, which we want to deploy for multiple clients. Each client has their own specifications for the marketplace participants and therefore needs different fields in addition to the basic fields (title, address etc.) that we define beforehand. I am looking for a solution for the marketplace admin (which won't be us) to be able to add these extra fields, e.g. via Wagtail snippets. They could create a new Custom Field Snippet and define some options for it. The page admin for marketplace participants then needs to display these extra fields in its form (either in a custom tab or just below all the basic fields in the content panel). Is there a way for me to achieve this? I have managed to get the custom fields into the page form but without any kind of Wagtail styling. I am aware of the similar question here but unfortunately the answers there did not help and the scenario is slightly different here. In the question linked the extra field is in Python code in the model definition, something we want … -
What is the best way to create the following model in Django Rest Framework
I am currently in the process of creating a new model. The current model looks like this, DIET_OPTIONS = ( ('vegan', 'Vegan'), ('vegetarian', 'Vegetarian'), ('meat', 'Meat') ) class Madklub(models.Model): owner = models.ForeignKey(MyUser, related_name="owner", on_delete=models.CASCADE) dish = models.CharField(max_length=100) date = models.DateField() guests = models.PositiveIntegerField() active = models.BooleanField(default=True) participants = models.ManyToManyField(MyUser, related_name="participants") diet = ArrayField( models.CharField(choices=DIET_OPTIONS, max_length=10, default="vegetarian") ) Now the model should be quite simple, the most important fields are the two user relationships and the diet field. The idea is that one Madklub has an owner (a owner can have multiple Madklub). Each Madklub has a list of participants, whenever a Madklub is created it should start out with having only one participant, the owner itself. Now this is the first question, how would I go about doing that automatically, should I simply handle that in the view? Side note, the guests field is a field keeping track of how many non-user guests are invited/participates in the Madklub. Would there be a way to bind this to a user, somehow? Now another question is, as can be seen I currently have the diet field as an ArrayField this of course only works with a Postgres database. As I see it, … -
Heroku deployed app returns 500 error - how to further investigate this issue?
So I have an app deployed at https://cherry-app-fr4mk.ondigitalocean.app/. This returns a error 500 page even though I have DEBUG=TRUE. How to further debug this issue and why it doesn't show Django styled errors? DEBUG: Variables: -
Using sourcedefender with Django
I have a python Django code that I wish to encrypt and can still run the django server from the encrypted folder. I read the PyPi specifically under Integrating encrypted code with Django and I could not get it to work. My python Django project structure is as follows: -- backend ---- config directory (where the settings.py file, wsgi.py are) ---- services directory (contains multiple directories of which all are encrypted, service1, service2, service3 which contains the Django rest framework APIs and code logic) ---- manage.py -- requirements.txt For me, it is not important the config directory, manage.py, and requirements.txt to be encrypted. What is important is that the services directory is encrypted. So how can I achieve that? Here is what I have tried. cd backend sourcedefender --remove encrypt --password 1234abcd --salt dcba4321 services In the manage.py, and wsgi.py I add import sourcedefender to the very top and then run python3 -m sourcedefender manage.py runserver and I get ImportError: manage Any help is appreciated. -
How to Post line items in Django REST API
This GET Response data [ { "id": "055444eb-5c4d-445b-99cc-a01be17deeb7", "transaction_line_items": [ { "id": "5b0ea944-a032-4b8e-a29a-3f52e0863040", "title": "Sambar Powder", "description": "Sambar Powder 100g", "price": "10", "quantity": 1, "created_at": "2022-08-17T14:01:39.387406Z", "updated_at": "2022-08-17T14:01:39.387406Z" }, { "id": "ace1546b-12e4-4a6d-991e-b867cf64515a", "title": "Tomato", "description": "Tomato 10kg", "price": "20", "quantity": 10, "created_at": "2022-08-17T14:01:05.194278Z", "updated_at": "2022-08-17T14:01:05.194278Z" } ], "transaction_no": "6aa623a3", "cgst_per": 8, "igst_per": 8, "sgst_per": 0, "created_at": "2022-08-17T14:01:58.694463Z", "updated_at": "2022-08-17T14:01:58.694463Z", "account": "0b68e37e-ba15-4427-8a45-d48b152a42d5", "main_biiling_account": "edc9d792-ffdb-4122-8589-d499f05e4f7b" } ] This POST Request data { "transaction_line_items":[ { "title":"Tomato", "description":"2 kg Tomato", "price":"10", "quantity":2 }, { "title":"Fish", "description":"2 kg Fish", "price":"500", "quantity":2 } ], "cgst_per":"8", "igst_per":"8", "sgst_per":"0", "account":"edc9d792-ffdb-4122-8589-d499f05e4f7b", "main_biiling_account":"edc9d792-ffdb-4122-8589-d499f05e4f7b" } This POST Response data { "id": "dc2ed349-2e3b-42a3-9ce8-1ecd6f11a225", "transaction_line_items": [], "transaction_no": "6aa623a3", "cgst_per": 8, "igst_per": 8, "sgst_per": 0, "created_at": "2022-08-17T14:08:02.995195Z", "updated_at": "2022-08-17T14:08:02.995195Z", "account": "edc9d792-ffdb-4122-8589-d499f05e4f7b", "main_biiling_account": "edc9d792-ffdb-4122-8589-d499f05e4f7b" } View Code @api_view(['GET','POST']) @permission_classes([IsAuthenticated]) def apiTransactions(request,account_id): if request.method == 'GET': transactions = Transaction.objects.filter(account=account_id,account__user=request.user) serializer = TransactionSerializer(transactions, many=True) return Response(serializer.data) elif request.method == 'POST': data = request.data if (data["account"]==account_id): serializer = TransactionSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response({'meassage': 'Account ID not match'}, status=status.HTTP_400_BAD_REQUEST) Above I gave codes and JSON data. Why my line items aren't saved? When I enter data using the admin page it's working properly. When I use API it isn't saved properly. How … -
Django and Flutter wth http Plugin
I've created a REST API with Django and I want to use it in Fluter. I've created the endpoints and tested them; they work fine, I've also created the models in flutter. I've done the get all endpoint. I'm now struggling with how to decode the details endpoint and use it in Flutter. Anyone's thoughts ? -
how to apply bubble sort in django queryset
*how to sort object using bubble sort in django.TypeError: '<' not supported between instances of 'Product' and 'Product' -
What is the advantage of binding to a socket instead of an IP?
I'm following this guide to deploy a flask application to production using gunicorn I get to this line gunicorn --bind 0.0.0.0:5000 wsgi:app and it works perfectly After that the author recommends this instead gunicorn --workers 3 --bind unix:/home/movieapp/app.sock -m 777 wsgi:app So my (dumb) question: what is the advantage of binding to a socket instead of an IP? Thank you for your help! -
DRF: Serializer for different queryset
I have following serializer class VoteBaseSerializer(serializers.Serializer): likes = serializers.IntegerField() dislikes = serializers.IntegerField() is_voted = serializers.SerializerMethodField() def get_is_voted(self, obj): user = self.context.get('request').user vote = None if user.id: try: vote = Vote.objects.get(pk=obj.pk, user_id=user.id).choice except Vote.DoesNotExist: pass return vote My problem that i want yo use this serializer for different views. I have view that return article with prefetch_relted comments, then i annotate likes, dislikes and is_voted I have view that update vote object. And i want to return new condition. The problem in SerializerMethodField, when i trying get vote object In 1 case i'm working with post object and comment, then with reverse relation i get votes In 2 case i'm update vote by comment_id and there different lookups models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(blank=True) body = models.TextField() tags = TaggableManager(blank=True) pub_date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-pub_date'] class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) text = models.TextField(max_length=500) pub_date = models.DateTimeField(auto_now=True) parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE, related_name='children') class Meta: ordering = ['-pub_date'] class Vote(models.Model): comment = models.ForeignKey(Comment, on_delete=models.CASCADE, related_name='votes') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) choice = models.BooleanField(null=True) views.py class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer permission_classes = [IsOwnerOrAdminOrReadOnly] pagination_class = PostPagination lookup_field … -
how to create a API for user model in Django?
I am Trying To create a API for my custom user model to register a user and get details about current user that is logged in . I tried to Follow a tutorial but I faced 2 problems, 1.The confirmation password is not being hashed when creating a user, 2. The Get method didn't work. I hope any one can help me. This is my models.py: from django.db import models from django import forms # Create your models here. from django.db import models from django.contrib.auth.models import ( AbstractUser, BaseUserManager, AbstractBaseUser ) from django.forms import Widget from django.urls import reverse class CustomUserManager(BaseUserManager): def create_user(self,email,password=None,is_active=True,is_staff=False,is_admin=False): if not email: raise ValueError('User Must Have Email') if not password: raise ValueError('User Must Have Password') user_obj = self.model( email = self.normalize_email(email) ) user_obj.set_password(password)#change user password user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_staffuser(self,email,password=None): user = self.create_user( email, password = password, is_staff = True ) return user def create_superuser(self,email,password=None): user = self.create_user( email, password = password, is_staff = True, is_admin = True, ) return user class CustomUser(AbstractBaseUser): username = models.CharField(max_length= 200) first_name = models.CharField(max_length = 300) last_name = models.CharField(max_length = 300) email = models.EmailField(max_length=255,unique=True) password = models.CharField(max_length=100,) password_2 = models.CharField(max_length=100,) sub_to_newsletter … -
How to change type in Django_filter input?
I have Django_filters form: class ContainerFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): super(ContainerFilter, self).__init__(*args, **kwargs) self.filters['title'].label = 'Продукт' self.filters['status'].label = ' Первый Статус' self.filters['status1'].label = 'Второй Статус' start_date = DateFilter(label='Создан от', field_name='created', lookup_expr='gte') end_date = DateFilter(label='Создан до', field_name='created', lookup_expr='lte',) class Meta: model = Container fields = ('title', 'status', 'status1', 'warehouse', 'start_date', 'end_date') And I want to change the start_date input type from text to date. I add widgedts in Meta but it's give error also i did widgets to input but it still don't work. -
Why I'm Not Getting Lable Tag Even After Loading It On The Templates?
Here Is The Template Image :- templates.html I'm Facing Problem While Rendering Template ,The Issue Is That The {{field.lable_tag}} Is Not Working I'm supposed To Get Field Lable which Is Wrapped In HTML Here Is My HTML code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Index</title> </head> <body> <form action="" method="POST" novalidate> {%csrf_token%} {{form.non_field_error}} {% for field in form %} <div> {{field.lable_tag}} {{field}} {{field.errors|striptags}} </div> {%endfor%} <input type="submit" value="Submit"> </form> </body> </html> -
psycopg2.OperationalError: SSL SYSCALL error: EOF detected django Qcluster
Hi I'm trying to run a function as a background job from Django Qcluster and that jobs run for more than an hour based on the response of that job I update my Postgres table but when I get a response from Qcluster and try to update the table it gives me this error. How can I fix this error? psycopg2.OperationalError: SSL SYSCALL error: EOF detected. Qcluster setting: { "name": "sampleapp", "workers": 8, "recycle": 500, "compress": true, "save_limit": 250, "queue_limit": 500, "cpu_affinity": 1, "label": "Django Q", "max_attempts": 1, "attempt_count": 1, "catch_up": false, "redis": { "host": "127.0.0.1", "port": 6379, "db": 0 } } Django==3.1.7 django-q==1.3.9 Here is the complete stack trace: SSL SYSCALL error: EOF detected 15:36:35 [Q] ERROR Failed [kentucky-montana-west-alaska] - connection already closed : Traceback (most recent call last): File "/mnt/c/lyftrondatasync/LyftrondatasyncAPI/venv/lib/python3.9/site- packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.OperationalError: SSL SYSCALL error: EOF detected The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/mnt/c/lyftrondatasync/LyftrondatasyncAPI/connector/sync_utils.py", line 1361, in run_data_sync if not table_pipeline_json.count(): File "/mnt/c/lyftrondatasync/LyftrondatasyncAPI/venv/lib/python3.9/site- packages/django/db/models/query.py", line 411, in count return self.query.get_count(using=self.db) File "/mnt/c/lyftrondatasync/LyftrondatasyncAPI/venv/lib/python3.9/site- packages/django/db/models/sql/query.py", line 515, in get_count number = obj.get_aggregation(using, ['__count'])['__count'] File "/mnt/c/lyftrondatasync/LyftrondatasyncAPI/venv/lib/python3.9/site- packages/django/db/models/sql/query.py", line 500, in get_aggregation result = … -
How to filter queryset based on MethodSerializerField value?
I have serializers with SerializerMethodField field class EmployeeSerializer(serializers.Serializer): id = serializers.IntegerField() name = serializers.CharField() group_ids = serializers.SerializerMethodField() def get_group_ids(self): /* this method returns array of group_ids employee can me member of */ there is view: class EmployeeViewSet(GenericViewSet): serializer_class = EmployeeSerializer def get_queryset(self): return Employee.objects.all() If I want to list all employees I call this url and get the next resutl: http://localhost:8080/employees/ [ { "id": 1, "name": "Ann", "group_ids": [ 90, 100 ] }, { "id": 2, "name": "Tom", "group_ids": [ 90, 102 ] } ] I want to filter result by group_id. To have something like this: http://localhost:8080/employees/?group_id=102 and as a result I'll recieve only: [ { "id": 2, "name": "Tom", "group_ids": [ 90, 102 ] } ] Is there any options to filter queryset based on calculated value such as SerializerMethodField value? Thanks in advance