Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django template list not showing all the images
I am working on a Django project and its a simple product website which will look like: First page- 1.Electronics link 2.Toys link Second page after clicking on the link: For electronics I have 3 item listed and same for toys. How to show images of different product once user will click on it along with the list of items. I have index.html which will show 1.Electronics link,2.Toys link <!DOCTYPE html> {% load static %} <html> <head> <title></title> <link rel="stylesheet" href="{% static "productApp/css/index.css" %}" </head> <body> <h1>Welcome to our online shoping portal</h1> <ul> <li><a href="/electronics">Electronics<img src="productApp/images/electronics.jpeg"/></a></li> <li><a href="/toys">Toys</a></li> <li><a href="/shoes">Shoes</a></li> </ul> </body> </html> Product.html <!DOCTYPE html> {% load static %} <html> <head> <title></title> <link rel="stylesheet" href="{% static "productApp/css/product.css" %}" </head> <body> <h1>{{heading}}</h1> <ul> <!-- <img src="{% static "productApp/images/electronics.jpg"%}"/> --> <li>{{product1}}</li> <li>{{product2}}</li> <li>{{product3}}</li> </ul> </body> </html> -
NOT NULL constraint failed: app_User.user_id
I've made an abstractuser model so I can register users through email, and when I'm trying to register new user I get this error NOT NULL constraint failed: app_shahadati_user.user_id How can I fix this error? models.py class CustomUser(AbstractUser): username = None email = models.EmailField(_("email address"), unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class Shahadati_user(models.Model): user = models.OneToOneField(CustomUser,on_delete=models.CASCADE) user_nID=models.PositiveIntegerField() def __str__(self): return self.user.email forms.py class CustomUserCreateForm(forms.ModelForm): password = forms.CharField() password_validation = forms.CharField() class Meta: model = CustomUser fields = ['first_name','last_name','email'] def clean_password_validation(self): pwd1 = self.cleaned_data.get('password') pwd2 = self.cleaned_data.get('password_validation') if pwd1 and pwd2 and pwd1 != pwd2: raise ValidationError("Passwords don't match") return pwd2 def save(self, *args, **kwargs): self.instance.set_password(self.cleaned_data.get('password')) return super().save(*args, **kwargs) class ShahadatiUserForm(forms.ModelForm): class Meta: model = Shahadati_user fields =['user_nID'] views.py def user_reg(request): if request.method == 'POST': form = CustomUserCreateForm(request.POST, request.FILES) form_ShU = ShahadatiUserForm(request.POST,request.FILES) if form.is_valid() and form_ShU.is_valid(): form.save() form_ShU.save() else: pass return render(request, 'Register.html', {}) -
How do I get typing working in python mixins?
I have a mixin that will always be used with a specific type of class i.e. a subclass of widgets.Input I want to override a few methods using the mixin, and I'm referencing attributes that exist on widgets.Input in my custom methods How do I tell the python type system that this mixin extends the widgets.Input interface without inheriting from widgets.Input? Bonus: Can I tell the type system that this mixin can only be used with subclasses of widgets.Input? from django.forms import widgets class MaskedWidgetMixin: def format_value(self, value): return "" def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) # <--- super().get_context does not exist context["widget"]["attrs"] = self.build_attrs(self.attrs, attrs, value) # <--- self.attrs does not exist return context def build_attrs(self, base_attrs, extra_attrs=None, value: str = ""): attrs = super().build_attrs(base_attrs, extra_attrs) # <--- super().build_attrs does not exist if value: attrs.update({"placeholder": "* ENCRYPTED *", "required": False}) return attrs class EncryptedTextInputWidget(MaskedWidgetMixin, widgets.TextInput): pass class EncryptedTextareaWidget(MaskedWidgetMixin, widgets.Textarea): pass -
Django admin model
Подскажите пожалуйста, как в model переменной присвоить имя класса: Т.е. есть class abonents(models.Model) и нужно переменной name присвоить имя abonents Либо можно ли с class Meta: verbose_name = "ПРОВЕРКА ВСЕХ АБОНЕНТОВ " verbose_name_plural = " ПРОВЕРКА ВСЕХ АБОНЕНТОВ " Передать в list_display admin модели. ничего не могу найти в нете похожего -
how to optimise queries n+1 problem in django orm
I have the following queries: I need to resolve the n+1 problem. I have the following code: sesializers.py: from rest_framework import serializers from django.db.models import Prefetch, Subquery, OuterRef from .models import Item, Size, Price class SizeSerializer(serializers.ModelSerializer): price = serializers.SerializerMethodField('get_price') class Meta: model = Size fields = ['title', 'price'] def get_price(self, obj) -> int: price_qs = Price.objects.filter(size=obj) price = price_qs.first() return price.price class ItemSerializer(serializers.ModelSerializer): price = serializers.SerializerMethodField('get_min_price') brand_name = serializers.CharField(max_length=20) size = SizeSerializer(many=True) class Meta: model = Item fields = ['title', 'sku', 'price', 'brand_name', 'size'] def get_min_price(self, obj) -> int: price_sq = Subquery(Price.objects.filter(size=OuterRef('pk')).values('price')[:1]) size_qs = Size.objects.filter(item=obj).prefetch_related( Prefetch('price', queryset=Price.objects.all())).annotate(min_price=price_sq) prices = size_qs.values_list('min_price') return int(''.join([str(i) for i in min(prices)])) In def get_min_price I have tried to implement it. It seems to me that I understand it not completely. In models I have the following structure: Brand -> Item(brand_name as foreign key, related_name=item) -> Size(item as foreign key, related_name=size) -> Price(size as foreign key, related_name=price) Give the cue that I am doing not so UPD: It has to be optimized with Prefetch and Subquery -
Raw SQLite3 command in Django
I am trying to join 2 tables to display the orders that are matched to the username for the currently logged in user using SQLITE3, I have the SQL raw command written but I recieve the error: there is no such table Account. I have checked using the .tables sql command and the table is created and working. The program is also migrated without any errors but the Account table cant be found. views.py from .models import Account, Order from django.db import connection def account(request): # Retrieve the currently logged in user user=request.session.get("user_id") if user is not None: # Retrieve the user's orders using a SQL join with connection.cursor() as cursor: cursor.execute(''' SELECT a.Username, a.Email, o.Name, o.Surname, o.part FROM Account a INNER JOIN "Order" o ON a.Username = o.Username WHERE a.id = %s ''', [user]) rows = cursor.fetchall() orders = [] for row in rows: order = { 'Username': row[0], 'Email': row[1], 'Name': row[2], 'Surname': row[3], 'Part': row[4], } orders.append(order) print(orders) # Render the orders template with the orders data return render(request, 'orders.html', {'orders': orders}) else: return redirect(reverse("home")) the Account in line 11 is giving the error #models.py class Account(models.Model): #Only one id can be created id = models.AutoField(primary_key=True) #Uses … -
Django - HTML Select not staying selected
I am trying to keep the selected object selected in html after submitting form. Below is my view and html select form. Tried all solutions on stack overflow and all combinations when referring to object in template and making changes to my view, but no success in keeping the selected object selected. views.py def profile(request,pk): posts = Post.objects.filter(active=True, owner=request.user) comments = Comment.objects.filter(post_owner=request.user) filter_post = request.GET.get('filter_post') if filter_post: comments = Comment.objects.filter(post_owner=request.user, post__exact=filter_post) ### Tried post_id, post__id, instead of post__exact return render(request, 'profile.html', {'posts':posts, 'comments':comments, 'filter_post':filter_post}) profile.html <form method="GET"> <select class="form-select" id="filter_post" name='filter_post'> <option value=""{% if value == "" %}selected {% endif %}> Select post </option> {% for post in posts %} <option value="{{post.id}}" {% if post.id == filter_post %} selected="selected" {% endif %}> {{post.title}} - {{post.created}} </option> {% endfor %} </select> </form> What am I doing incorrectly? -
Find filter entries from django whose sum is match with given amount
I have the following entries in my database code amount created_date is_used A 10 20/02/2023 0 B 10 20/02/2023 0 C 50 20/02/2023 0 D 50 20/02/2023 0 E 100 20/02/2023 0 I want to find out the entries from the above table in descending order by the amount that will match the sum of the amount with a given amount Example User enters 150 amount Expected result code amount created_date is_used E 100 20/02/2023 0 D 50 20/02/2023 0 I tried following but I want only required entries only queryset = MyModel.objects.filter(is_used=0).order_by('-amount', '-created_date') amount = 150 finalized_amount = [] for q in queryset: if amount == 0: break elif amount == q.amount: finalized_amount.append(q) amount -= q.amount elif q.amount < amount: finalized_amount.append(q) amount -= q.amount elif q.amount > amount: amt = q.amount - amount if amt <= 50 : finalized_amount.append(q) amount = 0 I know this is not a good solution. Please let me know if there is any to get these entries from the database in filter queryset only -
Djagno - custom User model with two factor auth - invalid credentials leads to creating a new user in database, valid credentials work, 2FA also
I have a django project, where i have custom user model stated as below : class CustomUserModel(AbstractUser): # MAKING email field mandatory email = models.EmailField(unique=True) # KEEP TRACK OF USER'S PASSWORD CREATION DATE TO ENFORCE 3MONTH MAX VALIDITY password_created_date = models.DateTimeField(default=timezone.now, null=False, blank=False) # WHICH DEPARTMENT IS USER MEMBER OF department = models.ForeignKey(Department, on_delete=models.PROTECT, default=1, null=False, blank=False) # WHICH TEAM IS USER MEMBER OF team = models.ForeignKey(Team, on_delete=models.PROTECT, default=1, null=False, blank=False) # USER TYPE - DETERMINES SOME ATTRIBUTES FOR USER - I.E. MAX AMOUNT OF ACTIVITY user_type = models.ForeignKey(UserType, on_delete=models.PROTECT, default=1, null=False,blank=False) # FIRST NAME - REQUIRED FIELD first_name = models.CharField(max_length=30, blank=False, null=False) # LAST NAME - REQUIRED FIELD last_name = models.CharField(max_length=30, blank=False, null=False) # OVERRIDE DEFAULT SAVE METHOD FOR USER THAT EMAIL IS REQUIRED ELSE - ValueError def save(self, *args, **kwargs): if not self.email: raise ValueError("Email field is required") super().save(*args, **kwargs) # OVERRIDE DEFAULT SAVE PASSWORD METHOD SO THAT DATE OF CREATION IS ALSO CREATED def set_password(self, raw_password): super().set_password(raw_password) self.password_created_date = timezone.now() self.save() In my settings.py i have included AUTH_USER_MODEL = 'attendance.CustomUserModel' here is error flow: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/account/login/ Django Version: 4.1.7 Python Version: 3.9.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'attendance', 'services', … -
Pycharm Django Run Error: CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False
When I start application I get following error: CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False How can I solve the problem? I want the program run with settings that I provided in settings.py file. -
How do I inspect objects passed to a custom save_model form in Django?
I'm working on overwriting a django save_model function, I want to do some debugging on the objects that get passed to it i.e. self, request: str, obj: ModelName, form: forms.ModelForm, change: str . Is it possible to "catch" those so I can play around with them in the shell? I've been printing and looking at them in the docker logs -
django deployment on aws elastic beanstalk
i have been struggling to deploy my django application on elastic beanstalk even after trying for many hours (i am using amazon linux 2, i dont know how to check this, but i am quite sure as i remember that this was the default setting when creating the elastic beanstalk application). i keep getting the following error: Mar 20 14:17:51 ip-10-0-2-193 web: ModuleNotFoundError: No module named 'gb_backend.wsgi' Mar 20 14:17:51 ip-10-0-2-193 web: [2023-03-20 14:17:51 +0000] [8829] [INFO] Worker exiting (pid: 8829) Mar 20 14:17:51 ip-10-0-2-193 web: [2023-03-20 14:17:51 +0000] [8823] [INFO] Shutting down: Master Mar 20 14:17:51 ip-10-0-2-193 web: [2023-03-20 14:17:51 +0000] [8823] [INFO] Reason: Worker failed to boot. Mar 20 14:17:52 ip-10-0-2-193 web: [2023-03-20 14:17:52 +0000] [8834] [INFO] Starting gunicorn 20.1.0 Mar 20 14:17:52 ip-10-0-2-193 web: [2023-03-20 14:17:52 +0000] [8834] [INFO] Listening at: http://127.0.0.1:8000 (8834) Mar 20 14:17:52 ip-10-0-2-193 web: [2023-03-20 14:17:52 +0000] [8834] [INFO] Using worker: gthread Mar 20 14:17:52 ip-10-0-2-193 web: [2023-03-20 14:17:52 +0000] [8840] [INFO] Booting worker with pid: 8840 Mar 20 14:17:52 ip-10-0-2-193 web: [2023-03-20 14:17:52 +0000] [8840] [ERROR] Exception in worker process Mar 20 14:17:52 ip-10-0-2-193 web: Traceback (most recent call last): Mar 20 14:17:52 ip-10-0-2-193 web: File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker Mar … -
Hardware requirements for Django server [closed]
What are the CPU and RAM recommended requirements for a Django server. It will have 200k transactions per day and 100 users, it will send requests to a database server. The database server is separate. I am asking only for the Django server. I am considering using 2gb RAM and 2.0 GHZ dual core. Would this be enough? -
d3js pan and zoom working with Five server test, but not with django runserver test
I made a test version of my code to use five server in vscode. I have managed to get pan and zoom to work via this example. I have moved all the javascript code changes to my django code set. However when I run this locally using the python manage.py runserver, the changes do not seem to have taken affect. As if I changed nothing in the code. I have tried clearing cookies and cache but that does not seem to make any difference. Here is the five server version: index.html: <!DOCTYPE html> <html> <head> <title>Tree</title> <link rel="stylesheet" href="static/css/style.css"> </head> <body> <script src="https://d3js.org/d3.v7.min.js"></script> <div id="plot"> </div> <script src="static/script.js"></script> </body> </html> script.js: d3.json("data/data_science.json").then(function(data) { console.log(data); // Set the dimensions and margins of the diagram // var margin = {top: 450, right: 90, bottom: 650, left: 275}, width = screen.width - margin.left - margin.right, height = screen.height - margin.top - margin.bottom; // append the svg object to the body of the page // appends a 'group' element to 'svg' // moves the 'group' element to the top left margin var i = 0, duration = 750, root; // declares a tree layout and assigns the size var treemap = d3.tree().size([height, width]).nodeSize([50, 40]); … -
How to retrieve value from dictionary with dynamic key in Django Template
I need to fetch and display the the value from dictionary using dynamic key in Django template. Model: class StatusData(models.Model): app= models.CharField(max_length=35) status= models.CharField(max_length=3) //possible values - SNY,DVL,TST class Meta: managed = False def __str__(self): return self.status view.py all_choices = {'SNY':'Sanity', 'DVL':'Develop', 'TST':'Testing'} model = StatusData.objects.order_by('-app') context = { "choices": all_choices, "modelData": model, } Django template: <html> {% for model%} <table> <tr> <td>{{ model.id }}</td> <td>{{ choices.model.status }}</td> // -- problem line </tr> </table> {% endfor %} </html> If I hardcode any specific key like {{ choices.SNY }} - it's deriving the the value as expected. How can I fetch the value by using the dynamic key that is returned by model.status i.e., {{ choices.model.status }}? -
how to run system commands inside a linux container or specify in Dockerfile?
I have created a Dockerfile for Djnago application and i want to run using a "gunicorn.service" file which have copied inside a /etc/systemd/system folder of an ubuntu container and i want to enable that Gunicorn service, but while using system or systemctl command it is showing command not found . what should do ? Expecting a Gunicorn automatically running in a background . -
How to refer to an inherited model in django
As in the title, that is, how to refer to an inherited model in django. I'm struggling with using the model_name function which returns the model name but it's not going the way I'd like. models.py class Product(PolymorphicModel): title = models.CharField(max_length=100, blank=True) image = models.ImageField(upload_to='product', default=None) quantity = models.IntegerField(null=False) is_available = models.BooleanField(default=True, null=False) price = models.IntegerField(null=False, blank=False, default=15) popularity = models.IntegerField(default=0) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse("ProductDetail", args=[str(self.pk)]) @property def model_name(self): return self._meta.model_name class CD(Product): GENRE_CHOICES = ( ('Disco', 'Disco'), ('Electronic music', 'Electronic music'), ('Rap', 'Rap'), ('Reggae', 'Reggae'), ('Rock', 'Rock'), ('Pop', 'Pop'), ) band = models.CharField(max_length=100, null=False, blank=False) tracklist = models.TextField(max_length=500, null=False, blank=False) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, null=False, blank=False) class Book(Product): GENRE_CHOICES = ( ('Biography', 'Biography'), ('Criminal', 'Criminal'), ('Fantasy', 'Fantasy'), ('Historical Novel', 'Historical Novel'), ('Horror', 'Horror'), ('Romance', 'Romance'), ('Sci-Fi', 'Sci-Fi'), ) author = models.CharField(max_length=100, null=False, blank=False) isbn = models.CharField(max_length=100, null=False, blank=False, unique=True) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, null=False, blank=False) class Film(Product): GENRE_CHOICES = ( ('Adventure', 'Adventure'), ('Animated', 'Animated'), ('Comedy', 'Comedy'), ('Horror', 'Horror'), ('Thriller', 'Thriller'), ('Romance', 'Romance'), ) director = models.CharField(max_length=100, null=False, blank=False) duration = models.IntegerField(null=False, blank=False) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, null=False, blank=False) views.py class Statistics(ListView): model = Product template_name = 'orders/statistics.html' def get_queryset(self): qs = super(Statistics, self).get_queryset() if self.request.GET: … -
using gunicorn in django xhtml2pdf doesn't render the images on pdf
using gunicorn for a program that must run on the local network when I request the pdf the images do not appear. In the home site, the css and images all appear, but the image does not appear when you request the pdf. I noticed that when loading the pdf, if I put the absolute path "http://localhost:8080/static/media/img.jpg in the html, it doesn't really resolve the request. I tried entering various solutions in the html image src, but it didn't solve the problem. I entered both {{ STATIC_ROOT }} from reading other solutions, and also tried {%static%} but the image is still not displayed. -
How to add a new field to the default user model in Django?
I want to add a new field to default Django user. I created a AbstractUser inherited model and added to the settings.py but I getting this error: ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'fdaconfig.customuser', but app 'fdaconfig' doesn't provide model 'customuser'. The field fdaconfig.Dataset.user was declared with a lazy reference to 'fdaconfig.customuser', but app 'fdaconfig' doesn't provide model 'customuser'. models.py class CustomUser(AbstractUser): user_info = models.CharField(max_length=255) settings.py AUTH_USER_MODEL = 'fdaconfig.customuser' -
Correct way to use a local Django project in a new computer (VS Code)
I created my first local Python/Django project a few months ago using Visual Studio Code. It worked perfectly. Now I'm trying to use it on a new computer. I've tried just saving the VS workspace and then loading it on the new computer, but it gives me the following error: ModuleNotFoundError: No module named 'gad' I think it's coming from the line os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gad.settings') in manage.py I don't know if I should create a Django project from scratch and then copy my "old" files into that project, if I just have to create the "gad.settings" file or what. I don't have the old computer, but I think I have all the files from my old Django project (but there is no gad.settings file in it, so maybe I had to copy more files outside that folder). Thanks! -
How to validate JSON from API via serializer
I'm new in Django anf I know how to use model serializers, but I can't find information about how to validate data from API. For example, I have a method that gets a data from another web service. def get_sales(self): url = "https://statistics-api.com/api/v1/sales" body = {"dateFrom": f"{datetime.datetime.now().date() - datetime.timedelta(days=30)}"} try: request = requests.get(url, params=body) if request.status_code == 200: return True, request.json() return False, request.json()["errors"] except json.JSONDecodeError as e: return False, f"Response is not in JSON format" The response is in JSON format. Smth like this: (True, [{'date': '2023-03-03T13:02:22', 'barcode': '46134548641', 'totalPrice': 500, 'discountPercent': 52}] So, I need to get the data from response in my views.py: sales = api.get_sales() result, sales_info = sales if result: try: prices_count = [] for element in sales_info: price = element.get("totalPrice", "") prices_count.append(price) transactions_total = sum(prices_count) I know this is not the best practice, because of KeyError. How can I validate data via serializer? -
Connection closed before receiving a handshake response daphne+Gunicorn in docker
So im trying to set up project where websocket connection will be handled by daphne, and all the other things with gunicorn. Also i have nginx installed. When im assessing webpage where should be connected to websocket - websocket returns 200, and message (index):16 WebSocket connection to 'ws://localhost:9000/application/ws/endpoint/' failed: Connection closed before receiving a handshake response. Im completely out of ideas, what have i missed in configurations. It seems like client simply can't connect to daphne server, and i cant understand why. here is my docker-compose file: version: '3.9' services: db: container_name: postgres image: postgres:14.6 volumes: - ./init.sql:/docker-entrypoint-initdb.d/init.sql - ./postgres_data:/var/lib/postgresql/data/ - .:/app environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - "POSTGRES_HOST_AUTH_METHOD=trust" restart: "on-failure" networks: - assemble nginx: build: ./nginx networks: - assemble volumes: - ./nginx/cert:/nginx/cert ports: - "80:80" - "443:433" depends_on: - db - daphne redis: image: redis networks: - assemble ports: - 6379:6379 depends_on: - db daphne: build: context: ./WebService dockerfile: Dockerfile image: latest volumes: - ./static:/engine_side/static - .:/app networks: - assemble depends_on: - db - gunicorn - redis ports: - 9000:9000 expose: - 9000 gunicorn: build: context: ./WebService dockerfile: Dockerfile volumes: - .:/app - ./static:/engine_side/static environment: - DJANGO_SUPERUSER_USERNAME=${DJANGO_SU_USERNAME} - DJANGO_SUPERUSER_PASSWORD=${DJANGO_SU_PASSWORD} - DJANGO_SUPERUSER_EMAIL=${DJANGO_SU_EMAIL} - POSTGRES_NAME=${DB_NAME} - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} … -
Time and date calculations DJango
So i have a data entry project using django and i have those 4 fields representing the: start_date, start_time, end_date, and end_time {% block content %} <h1>Form Page</h1> {% csrf_token %} {{ form.start_date.label_tag }} {{ form.start_date }} {{ form.start_time.label_tag }} {{ form.start_time }} {{ form.end_date.label_tag }} {{ form.end_date }} {{ form.end_time.label_tag }} {{ form.end_time }} {{ form.duration_hours.label_tag }} {{ form.duration_hours }} Submit {% endblock %} so the thing that i need is to make a listener for those 4 field values and whenever the user entered the first 3 values and start filling up the forth one which will be the end time the duration_hours field will start to calculate the difference between and give me the value of the duration time. All models,forms python files are correct i just want to know how i can do it I tried to make a script in the html file like this : <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"\>\</script\> $(document).ready(function(){ // get the values of the start and end date/time fields var start_date = $("#start_date input").val(); var start_time = $("#start_time input").val(); var end_date = $("#end_date input").val(); var end_time = $("#end_time input").val(); // combine the start date/time and end date/time into Date objects var start_datetime = new … -
Count objects in queryset by value in a field
I have a queryset that is returned by the server: queryset = Item.objects.all() ItemSerializer(queryset, many=True).data [OrderedDict([('id', '123'), ('status', 'Available')]), ... OrderedDict([('id', '321'), ('status', 'Confirmed')])] I can get the number of items by status: queryset.values('status').annotate(Count('status')) <QuerySet [{'status': 'Available', 'status__count': 3}, {'status': 'Confirmed', 'status__count': 2}]> As a result, I am trying to get such a response from the server: [{"id":"123","status":"Available"}, ... {"id":"321","status":"Confirmed"}, {"status": "Available", "status__count": 3}, {"status": "Confirmed", "status__count": 2}] -
Tools to help in analyzing and reviewing large python code base
I have a large Django code base which I want to analyze and review.Is there any tools that can help me to do this efficiently like explain the code architecture,flow and give me high level overview?