Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django how to dynamically create nested and or queries
I have two types of filter list looking like below a_filter = ['a', 'b', 'c'] b_filter = ['x', 'y', 'z'] I have to combine the in query for a_filter and boolean field query for b_filter something like below Item.objects.filter(a__in=a_filter, x=True, y=True, z=True) How do I dynamically create this query? I got as far as below filters = { a_filter__in:a_filter, } and_condition = Q(**filters) if len(b_filter) > 0: or_cond = Q() for filter in b_filter: or_cond.add(Q(**{filter:True}), Q.AND) and_condition.add(or_filter) Item.objects.filter(and_condition) This create additional (OR: (AND: ) in between the two filter queries like below (AND: 'a_filter__in': ['a', 'b', 'c'), (OR: (AND: ), (AND:('x':True, 'y':True, 'z':True)) How do I write a correctly working query? -
Javascript issue with Django Debug toolbar
I am currently building an application with Django and using the Django Debug Toolbar to optimize it. When I run my application (with DEBUG = True, in my dev environment), I frequently (but not always...) get the following JavaScript error (toolbar.js:227): Because of that, the toolbar does not appear correctly. I am using Django 3.0 and the django-debug-toolbar 2.1 (and Chrome 80.0.3987). Any help appreciated. Thank you in advance. -
Connect Postgres DB and Models (Django & Flask) in Docker containers
I have Docker Containers application with Flask and Django containers. It is possible share Database between Django container and Flask Container? django: &django ... depends_on: - postgres flask: ... ports: - "5090:5090" ... - postgres links: - postgres postgres: build: ... env_file: - ./.envs/.local/.postgres Models are in Django application. So, I need to do a Login in Flask Application using Postgres Database. The problem is, I only want to use the connection to Database, I do not need to do models in Flask. I used Sqlalchemy method: if form.validate_on_submit(): query = session.query(User) login = User.query.filter(username=form.username.data).first() if login is not None: print(login) return redirect(url_for('index')) return render_template('login.html', form=form) And I tried with Panda method: if form.validate_on_submit(): sql = "SELECT * from users WHERE username = '{0}'".format(form.username.data) login = pd.read_sql_query(sql,SQLALCHEMY_DATABASE_URI) if login is not None: print(login) return redirect(url_for('index')) But the error is the same in both cases, I need to do a relation, so, it is a Migration, in Flask. **sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "users"** It is my database.py: ... SQLALCHEMY_DATABASE_URI = 'postgres://%s:%s@%s:%s/%s' % (user, pwd, host, port, db) SQLALCHEMY_TRACK_MODIFICATIONS = os.environ.get('SQLALCHEMY_TRACK_MODIFICATIONS') db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) def init_db(): ... -
how do I properly set up data validation?
I have a DRF class which receives JSON date and after it has been processed, create new database instances. class CsvToDatabase(APIView): def post(self, request, format=None): data = request.data print() for _, vendor in data.items(): v = Vendors( vendor_name=vendor['Vendor'], country=vendor['Country'], nda=vendor['NDA date'], ) try: v.full_clean() except ValidationError as e: data = ({'status': str(e)}) return Response(data, content_type='application/json') v.save() return Response({'received data': request.data, 'message': 'Vendors from vendors_list were successfully added to the database'}) models.py class Vendors(models.Model): COUNTRY_CHOICES = tuple(countries) ... country = models.CharField(max_length=45, choices=COUNTRY_CHOICES) nda = models.DateField(blank=True, null=True) ... tuple(countries) looks like: (..., ('AR', 'Argentina'), ('AM', 'Armenia'), ('AW', 'Aruba'), ('AU', 'Australia'), ('AT', 'Austria'), ('AZ', 'Azerbaijan'), ('BS', 'Bahamas'), ('BH', 'Bahrain'), ('BD', 'Bangladesh'), ('BB', 'Barbados'), ('BY', 'Belarus'), ('BE', 'Belgium'), ...) Received JSON data may or may not contain the value of the nda field. An example of an incoming data format is as follows { "1": { "Vendor": "Firstvendortestname", "Country": "Belgium,", "NDA date": "", "Primary Contact Name": "Jack Jhonson", "Primary Contact Email": "jack@gmail.com", "Secondary Contact Name": "Jack2 Jhonson", "Secondary Contact Email": "jack2@gmail.com", "Modules": "Module1, Module2" }, "2": { "Vendor": "Secondvendortestname", "Country": "Belarus", "NDA date": "2019-12-24", "Primary Contact Name": "Sandra Bullock", "Primary Contact Email": "sandra@gmail.com", "Secondary Contact Name": "Sandra Bullock", "Secondary Contact Email": "sandra@gmail.com", "Modules": "Module1, … -
Django users and permissions
I need to develop a scenario of users and groups in my django application there are three groups - Admin - Manager - Employee Generally admin is available by creating superuser and I need to create the users for different groups - Admin can access all the records created by all users Now my requirement is some users are belongs manager group and some normal users belongs to employee group.. How he associate user belongs to manager group can fetch his own records along with his subordinate users from employee group I'm fully confused to give relation between normal users with an associate user from manager group... simply How can I assign some employee users to a manager user please anyone help me out by sharing a best approach...Thanks in advance -
User manually create model fields for post [django]
So I want to create a post by letting the user add a section/subtitle as they need it, but I have no idea how to go about creating this, I currently just have a title, preview and content block in a form but want the user to be able to create as many subtitle and content blocks as they want. Any help is very much appreciated :) -
Django Many-To-One
I'm trying to create a simple to-do app in Django. I have some trouble to understand the idea of foreign keys. Each project suppose to get multiple apartments, and each apartment should get multiple tasks. models: # Project model class Project(models.Model): name = models.CharField(_("Name"), max_length=30) city = models.CharField(_("City"), max_length=30) street = models.CharField(_("Street"), max_length=30) number = models.IntegerField(_("Number"), max_length=4) ZIP = models.ImageField(_("ZIP"), max_length=10) manager = models.CharField(_("Manager"), choices=managers, default='ariel') # Apartments apartment = models.ForeignKey(_("Apartment"), Apartment, on_delete=models.CASCADE) def __repr__(self): return "{}".format(self.name) # Apartment model class Apartment(models.Model): building = models.CharField(_("Building"), max_length=4) floor = models.CharField(_("Floor"), max_length=4) number = models.CharField(_("Number"), max_length=4) type = models.CharField(_("Type"), max_length=4) upgraded = models.BooleanField(_("Upgraded"), default=False) drawing = models.FileField(_("Drawing"), upload_to=None) notes = models.TextField(_("Notes"), max_length=500) status = models.BooleanField(_("Completed"), default=False) # Tasks airTunnels = models.ForeignKey(_("Air Tunnels"), Task, on_delete=models.CASCADE) gasPipelines = models.ForeignKey(_("Gas Pipelines"), Task, on_delete=models.CASCADE) def __repr__(self): return "{} - {}".format(self.number, self.status) # Task model class Task(models.Model): title = models.CharField(_("Task"), max_length=30) doneBy = models.CharField(_("Done By"), choices=workers, default='daniel') date = models.DateTimeField(_("Date"), default=timezone.now()) def __repr__(self): return "{}".format(self.title) -
DJango FTP:: TimeoutError: [Errno 110] Connection timed out
getting error while connecting to ftp in django server.connect('68.183.91.171') File "/usr/lib/python3.6/ftplib.py", line 152, in connect source_address=self.source_address) File "/usr/lib/python3.6/socket.py", line 724, in create_connection raise err File "/usr/lib/python3.6/socket.py", line 713, in create_connection sock.connect(sa) TimeoutError: [Errno 110] Connection timed out settings.py import ftplib server = ftplib.FTP() server.connect('68.183.91.171') server.login('root','password') server.dir() I think the connection is proper but I am not sure why I am getting this error, it would be great if anyone can help me figure out what I am doing wrong -
How to csrf_token in asynchoronous post with jquery
I found several posts in relation to my question, but none of them solves my problem. I am sending data to the server but I keep getting a 403-error with an error-message that complains about the csrf_token. Here is my html: <ul id="EditorNav" class="editor-nav"> <form id="NavItemsEditorForm" class="nav-items-editor-form"> {% csrf_token %} <!-- {{ form }} --> {% for item in pages %} <input class="editor-nav-input" type="text" value="{{ item }}"/> {% endfor %} </form> <img id="Plus" class="plus" src="{% static 'img/plus.png' %}" alt="Plus" title="Een menu-item toevoegen" /> <img id="Shuffle" class="shuffle" src="{% static 'img/shuffle.png' %}" alt="Shuffle" title="Verander de volgorde van de menu-items" /> <button id="NavEditReady" class="nav-edit-ready">Klaar</button> </ul> I created a view and added that view to the urlpatterns-arrau in urls.py. Here is my javascript: jQuery.each( jQuery( '.editor-nav-input' ), function( i ){ let data = {} if( jQuery( this ).val() === '' ) { jQuery( this ).remove(); }else{ const idx = jQuery( '.editor-nav-input' ).index( this ); const tekst = jQuery( '.editor-nav-input' ).eq( idx ).val(); data = { "id": idx, "tekst": tekst, "href": tekst.replace(/\s/g, '_').toLowerCase(), "volgorde": idx + 1, }; formdata.push( data ); } }); console.log( formdata ); // Stuur de data naar de server: jQuery.ajax({ method: "POST", url: "/pagepost/", headers: { 'X-CSRFToken': '{{ csrf_token }}' }, … -
Upload Large files Django Storages to AWS S3
I am a new Django, and I have a project that should upload large files (sizes from 5G+). I am using: django-storages Amazon S3 Django 3.0.2 Python 3.7.6 JQuery 3.1 In documentation, it says that when the file is larger than 2.5MB, it goes to TemporaryFileUploadHander, which means it goes to /tmp directory first and when the upload is complete, it moves the file to Media Root (which in my case it is the Amazon S3) Now, the requirement is to stream the upload of file to Amazon S3. For example: 20Gb file should be uploaded in stream (little by little) to Amazon S3. How can I implement this requirement to upload the file directly to Amazon S3 directly without having it first in /tmp directory. Please help. -
How to generate aggregate values from a database
I am working on an API with Django Rest Framework. I want to generate daily/weekly/monthly/annual aggregate values for total bookings that have happened. I have added an image to give an idea of how the aggregated weekly data may look. Here is simplified model. Most of the queries I attempted failed to achieve what I wanted. class Booking(models.Model): amount_paid = models.DecimalField(decimal_places=2, max_digits=20) trans_date = models.DateField(auto_now=True) -
How to process messages with django-channels 2?
Within my Django project, I created a notification app that detect whenever a specific model is saved and push a notification to all clients (based on https://arunrocks.com/understanding-django-channels/ and https://github.com/arocks/channels-example ). I have updated my code to Channels 2 and I have now an issue with the javascript wrapper which has been removed in the django-channels 2(How to locate websocketbridge.js in Django using channels websocket?) Before I had a script that processes messages: <script> document.addEventListener('DOMContentLoaded', function() { const webSocketBridge = new channels.WebSocketBridge(); const nl = document.querySelector("#notifylist"); webSocketBridge.connect('/notifications/'); webSocketBridge.listen(function(action, stream) { console.log("RESPONSE:", action); if(action.event == "New User") { var el = document.createElement("li"); el.innerHTML = action.text; nl.appendChild(el); } }) }) </script> This script doesn't work anymore. They suggested to replace WebSocketBridge.js by ReconnectingWebSocket.js but I don't know how I can adapt my previous script in order to use ReconnectingWebSocket.js. Has anyone updated his/her code by using ReconnectingWebSocket? If so, could you, please, provide an example. Many thanks in advance for your help. -
Django converting year to a full date
In my book aplication I have a date field in model, but as an input from REST request sometimes I am getting just a year, or even full date but as a string format. I wanted to create at first a manual form to add a books where i don't know exact date of publication despite a year. So what I am trying to do is in case of getting just a year add "01/01" and convert is to a date with ".strptime(s, "%Y-%m-%d").date()". But that's not working, datefield default validator is preventing me from passing anything else than "yyyy-mm-dd" format input. Can i somehow overwrite a default validaotr or stop launching it by a form ? Any suggestion how to handle that problem? Models: class Book(models.Model): title = models.CharField(max_length=100) publication_date = models.DateField() authors = models.ManyToManyField("Author", related_name="author") ISBN = ISBNField() #validators=[book_unique_validator,] pages = models.IntegerField(validators=[page_validator,], blank=True) language = models.CharField(max_length=4) def __str__(self): return self.title views: class BookAddView(FormView): model = Book template_name = "Books/create_book.html" form_class = BookForm success_url = reverse_lazy("book_list") def form_valid(self, form): if Book.objects.filter(ISBN=form.cleaned_data["ISBN"]).count() > 0: messages.warning(self.request, f'Book "{form.cleaned_data["ISBN"]}" already exist in database.') return redirect("book_details", pk=Book.objects.get(ISBN=form.cleaned_data["ISBN"]).pk) else: if len(publication_date=form.cleaned_data['publication_date']) == 4: book_date = (form.cleaned_data['publication_date'] + "01/01").strptime(s, "%Y-%m-%d").date() else: book_date = publication_date=form.cleaned_data['publication_date'] new_book … -
Django template doesn't show latest changes
I am using django all auth templates and I want to customize it but the problem is, whenever I make changes it keep showing the previous template and won't updating, I have also clear the browser cache but still same problem: password_reset_form.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Password Change</title> </head> <body> <form method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit">Submit</button> </form> </body> </html> I am trying to customize above template.I have not used base.html here's my settings.py """ Django settings for TheifDetection project. Generated by 'django-admin startproject' using Django 3.0.2. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os import datetime # Build paths inside the project like this: os.path.join(BASE_DIR, ...) from distutils.command.config import config import dj_database_url from django.conf.global_settings import DATABASES BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ DEBUG = True ALLOWED_HOSTS = ['127.0.0.1'] # Application definition INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'UserAuth.apps.UserauthConfig', 'DetectApp.apps.DetectappConfig', 'rest_framework', 'allauth', 'allauth.account', 'django.contrib.sites', 'rest_auth', 'corsheaders', ] SITE_ID=6 # or 7 6 AUTH_USER_MODEL='UserAuth.User' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'corsheaders.middleware.CorsMiddleware', # cors 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] # new … -
Post done to django model from Postman is successful to django rest api but from angular 7 leads to internal server error 500
angular 7 service code: export class LoignapiService { enter code herehttpHeader=new HttpHeaders({'Content-type':'application/json'}); enter code hereconstructor(private http:HttpClient) { } `enter code here`registerNewUser(userData) : Observable<any>{ `enter code here`return this.http.post('http://127.0.0.1:8000/'+'vie',userData,{headers:this.httpHeader}) } show():Observable<any>{ `enter code here`return this.http.get('http://127.0.0.1:8000/vie',{headers:this.httpHeader}) } } django view page: @csrf_exempt @api_view(['GET', 'POST']) def v(request): if request.method=='GET': enter code heredata1=UserLogin.objects.all() enter code hereserializer=UserLoginSerializer(data1,many=True) enter code herereturn JsonResponse(serializer.data,safe=False) elif request.method == 'POST': `enter code here`serializer = UserLoginSerializer(data=request.data) `enter code here`if serializer.is_valid(): `enter code here` serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) -
How can I display images in templates list view and detail view
I am building a website for computer sales.I have 3 images for each model, I want to display one of the 3 image in the list view for each product with some description,then on the details view, I want to have the 3 images organized in such a way that there is a frame for the main image, and a button to toggle to the other images along with some description. How can I achieve this? -
using ajax + django to submit forms
I am trying to make an order confirmation by mail. Fill out the form, the code arrives in the mail, enter the new form and get an answer about the success. views.py def get_name(request): if request.method == 'POST': user_code = generate_code(8) subject = 'code' message = user_code phone=request.POST['phone'] form = NameForm(request.POST) if form.is_valid(): date_use = form.cleaned_data.get("date_visit") time_use = form.cleaned_data.get("time_visit") purpose_use = form.cleaned_data.get("purpose") if Registration.objects.filter(date_visit=date_use,time_visit=time_use).count()==0: Registration.objects.create(fio=request.POST['fio'],phone=request.POST['phone'],date_visit=request.POST['date_visit'],time_visit=request.POST['time_visit'], phone=request.POST['phone']) request.session["phone"] = phone request.session["code"] = user_code send_mail(subject, message,settings.EMAIL_HOST_USER,[mail],fail_silently=False) return JsonResponse({ 'form1': render_to_string( 'registers/endreg.html', {'form': NameForm1(), }, request=request) }) else: form = NameForm() return render(request, 'registers/detail.html', {'form': form}) def endreg(request): name_phone = request.session.get("phone", " ") name_code = request.session.get("code", " ") if request.method == 'POST': form = NameForm1(request.POST) if form.is_valid(): code_use = form.cleaned_data.get("key") if (name_code == code_use): try: user = Registration.objects.get(phone=name_phone) user.verification = True user.save() return JsonResponse({ 'form2': 'thanks') except: return JsonResponse({ 'form2': 'error') else: form = NameForm1() return render(request, 'registers/endreg.html', {'form': form}) and ajax code $(document).ready(function() { $("#my_form").submit(function(event) { event.preventDefault(); $this = $(this); $.ajax({ type: "POST", data: $this.serialize(), success: function(data) { console.log(data); var parent=$("#my_form").parent(); parent.html(data.form1); }, error: function(data) { console.log(data); $this.html(data); } }); }); }); $(document).ready(function() { $("#my_form2").submit(function(event) { event.preventDefault(); $this = $(this); $.ajax({ type: "POST", data: $this.serialize(), success: function(data) { console.log(data); var parent=$("#my_form2").parent(); parent.html(data.form2); … -
django// display data with changeable context key variable
Django 2.2 python 3.6 I'm trying to display rawqueryset data in tempalte. However, those rawqueryset columns are not fixed, it's changeable. Becuase columns are changed by user posted(request) date range. For example, {% for foo in monthly_consult_by_dr %} <p>{{ foo.cnt_???? }}</p> <p>{{ foo.cnt_???? }}</p> <p>{{ foo.cnt_???? }}</p> <p>{{ foo.cnt_???? }}</p> <p>{{ foo.cnt_???? }}</p> <p>{{ foo.cnt_???? }}</p> {% endfor %} But I can find out which column is included in the code below. {% for key in monthly_consult_by_dr.colunms %} <p>{{ key }}</p> {% endfor %} ## result cnt_201812 cnt_201901 cnt_201902 cnt_201903 cnt_201904 cnt_201905 .... this is my views.py if you need.. def index_2_consult_detail(request): .... skip.... start_month = start_month_from_user_post_request end_month = end_month_from_user_post_request from dateutil.rrule import rrule, MONTHLY def months(start_month, end_month): start = datetime.datetime.strptime(start_month, '%Y-%m-%d') end = datetime.datetime.strptime(end_month, '%Y-%m-%d') return [str(d.year)+f"{d.month:02d}" for d in rrule(MONTHLY, dtstart=start, until=end)] month_list = months(start_month, end_month) insert_query_1_monthly_consult_by_dr = '' add_limit_number = len(month_list) insert_tb_row_start_month = month_list[0] for i in month_list: add_select = ''' , SUM(CASE WHEN M.BASE_TM = '{j}' THEN M.CNT ELSE 0 END) AS cnt_{j} , SUM(CASE WHEN M.BASE_TM = '{j}' AND M.C_TYPE = 'consulting' THEN M.CNT ELSE 0 END) AS consult_total_cnt__{j} , SUM(CASE WHEN M.BASE_TM = '{j}' AND M.C_TYPE = 'consulting' AND M.CONSULT_TYPE = 2 THEN M.CNT … -
Django Unable to rollback with try-exception block for atomic transactions
One of my view in Django executes save operations on 6-7 tables. I want these transactions to be atomic I,e if the 5th or 6th transaction fail I want to rollback all the previous saves. The view contains a try-except block to handle the exceptions raised. It looks something like this: @transaction.atomic def my_view(request): sid = transaction.savepoint() try: Table1.save() Table2.save() Table3.save() Table4.save() Table5.save() Table6.save() Table7.save() # This might fail. In case of failure I want to rollback saves from Table1 to Table6 transaction.savepoint_commit(sid) except Exception as e: print(str(e)) transaction.savepoint_rollback(sid) return JsonResponse({"Status": 0, "Data": str(e)}) I've tried the above and Table7.save() has failed and Table1 to Table6 rollback has not happened. I want to return the JSON response as {"Status": 0, Data: "Error That occurred"} in all the cases. I don't want to re-raise the exception in except block as done in This link What should I do to return a proper JSONResponse and rollback everything in case of failure? -
How to combine and get data from multiple tables for a single id
table A : ................ id name age | ................ 1 G 29 | 2 A 30 | ................ table B : (table b have the foreign key of table A in tableA_id field which comes multiple) id phone rank tableA_id 1 98989 A 1 2 98989 C 1 3 98989 D 2 table C : (table C have the foreign key of table A in tableA_id field which comes multiple) id notes email tableA_id 1 98989 A@gmail.com 1 2 98989 C@gmail.com 1 In my case i am want to get all the data from all the tables and want to display in a single page . the what i want is i want one single query to get the all data from all of three table with one query set. And id what i am sending is Table_id = 1 so how can i get the data for table 1 from all the tables can anyone have idea please let me now i am a new be here -
Django website hosted in a corporate network using waitress is not accessible from only one site/location in the network
Django website hosted in a corporate network using waitress is not accessible from only one particular location/site.. But people from other locations/site were able to access the website.. it was working earlier but suddenly stopped -
django test runner do not see tests on py2 version, but see them on py3
When I run a command on py3: python manage.py test myproject.user_management --settings mysettings.py I see all my tests working fine: Ran 29 tests But the same command on py2: Ran 0 tests Command on py2 is only working when I add tests folder to command, like: python manage.py test myproject.user_management.test --settings mysettings.py I already: 1. Double check my imports an __init__.py in all folders and sub folders 2. Settings etc. My app structure looks like: project_name ----user_management --------__init__.py --------tests ------------__init__.py ------------training ----------------__init__.py ----------------training.py In python manage.py shell I can easy do: from axis.user_management.tests import TrainingViewSetTest This behaviour happens only for few apps in my project. -
Django: How to add Django-Filter in settings.py
Git Repository I work according to this flow When I add this code inside my settings.py. REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'] } This error comes up. Request to guide me -
Exception: not authorised django while logging
while post operation in postman getting error,Exception: not authorised,why my user to unable to log in class UserLoginViewSet(viewsets.ViewSet): def create(self,request): try: data=request.data email=data.get('email') password=data.get('password') date_of_birth=data.get('date_of_birth') if not all([email,password]): raise Exception('all fields are mandetory') user=authenticate(email=email,password=password) print('h',email) print('b',password) print(user) if user is not None: token=generate_token() user_info=MyUser.objects.get(email=email) data=({ 'email':user_info.email, 'password':user_info.password, #'data_of_birth':user_info.data_of_birth }) return Response({"message": "You are successfully logged in", "user_info":data,"token": token, "success": True},status=status.HTTP_200_OK) else : raise Exception('not authorised') except Exception as error: traceback.print_exc() return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK) -
Django Rest Framework: Count Number of Objects with multiple ManyToManyField values
In the example below, I have two models with a ManyToMany relation and I'm trying to count the number of posts related to the tags. There are 3 tags: Sports, Films, Health There are 3 posts: 1 for Sports, 1 for Films and 1 post with two tags (Sports and Health) I can get the count of posts for every tag as below: [ { "name": "Sports", "posts": 2 }, { "name": "Films", "posts": 1 }, { "name": "Health", "posts": 1 } ] My requirement is to count the objects separately for the combination of tags. So, the desirable output is: [ { "name": "Sports", "posts": 1 }, { "name": "Films", "posts": 1 }, { "name": "Sports & Health", "posts": 1 } ] This is where I'm stuck. How do I combine the two tags and then count the number of post objects that have both these tags? models.py class Tag(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() tags = models.ManyToManyField(Tag) def __str__(self): return self.title serializers.py class TagSerializer(serializers.ModelSerializer): posts = serializers.SerializerMethodField() class Meta: model = Tag fields = ('name', 'posts') def get_posts(self, obj): posts = obj.post_set.all().count() return posts class PostSerializer(serializers.ModelSerializer): class Meta: …