Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django annotate based on another annotate create a duplicate query
I want to calculate number of group members (no_members), sum of the points of the group members(point) and average point per person(avg_point) for each group with annotation: groups = StudyGroup.objects.filter(group_filter).select_related('parent').annotate( no_members=Count('student', distinct=True), point=Sum('student__point__point', filter=point_filter), avg_point=ExpressionWrapper(F('point') / F('no_members'), output_field=FloatField())) but when I check query (groups.query) in avg_point instead of use point/no_members query is SUM(study_league_point.point) / COUNT(DISTINCT users_student.user_id) (point and no_members calculate again). query is: SELECT `study_league_studygroup`.`id`, `study_league_studygroup`.`name`, `study_league_studygroup`.`parent_id`, COUNT(DISTINCT `users_student`.`user_id`) AS `no_members`, SUM(`study_league_point`.`point`) AS `point`, ( SUM(`study_league_point`.`point`) / COUNT(DISTINCT `users_student`.`user_id`) ) AS `avg_point`, `layers_layer`.`id`, `layers_layer`.`name`, `layers_layer`.`type_id`, `layers_layer`.`parent_id`, `layers_layer`.`created`, `layers_layer`.`default`, `layers_layer`.`lft`, `layers_layer`.`rght`, `layers_layer`.`tree_id`, `layers_layer`.`level` FROM `study_league_studygroup` LEFT OUTER JOIN `users_student` ON ( `study_league_studygroup`.`id` = `users_student`.`study_group_id` ) LEFT OUTER JOIN `study_league_point` ON ( `users_student`.`user_id` = `study_league_point`.`student_id` ) INNER JOIN `layers_layer` ON ( `study_league_studygroup`.`parent_id` = `layers_layer`.`id` ) GROUP BY `study_league_studygroup`.`id` but I want use (point / no_members) AS avg_point instead of (SUM(study_league_point.point) / COUNT(DISTINCT users_student.user_id)) AS avg_point -
What are Pharaoh, Grandmother, and Monarchy deletion patterns?
I was looking at the docs for Django CTE Trees and saw the text: Multiple delete semantics: supports Pharaoh, Grandmother, and Monarchy deletion patterns. This meant nothing to me, so I did a bit of googling - and found nothing! Does anyone know what "Pharaoh, Grandmother, and Monarchy deletion patterns" are? -
CKEditor in production not showing in admin panel
I've launched my project into production, CKEditior and CKEditor_uploader both worked on my local server but now doesn't show on my production admin panel. Any ideas why it may not be showing would be greatly appreciated. Or any alternative ways to implement richtext and image uploading to blog posts in django admin. settings.py STATIC_URL = '/static/' MEDIA_URL = '/static/images/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, '/home/martinhenso/public_html/static/images/') STATIC_ROOT = os.path.join(BASE_DIR, '/home/martinhenso/public_html/static') CKEDITOR_UPLOAD_PATH = "uploads/" urls urlpatterns = [ path('admin/', admin.site.urls), path('', include('martinhensonphotography.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.MEDIA_ROOT) models class Topic(models.Model): title = models.CharField(max_length=100) content = RichTextUploadingField() def __str__(self): return self.title class BlogPost(models.Model): blog_title = models.CharField(max_length=255) blog_article = RichTextField(null=True, blank=True) blog_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png") def __str__(self): return self.blog_title admin from django.contrib import admin from . models import PostImage, EnterImage, BlogPost, Topic # Register your models here. admin.site.register(PostImage) admin.site.register(BlogPost) admin.site.register(EnterImage) admin.site.register(Topic) -
django DenseRank annotation based on another annotate
I want to annotate rank queryset based on avg of points. annotate(avg=Avg('point'), rank=Window(expression=DenseRank(), order_by=Value("avg").desc()) but rank is 1 for all data. When I check query straight in database result is true! but in django all rank is 1. When I use F("avg") instead of Value("avg"), result is true but query is not optimal . With F() in query once calculate average of points for avg and calculate avg again for rank avg: query 1: SELECT AVG(point) AS avg, DENSE_RANK() OVER ( ORDER BY AVG(point) DESC ) rank, but I want below query: query 2: SELECT AVG(point) AS avg, DENSE_RANK() OVER ( ORDER BY avg DESC ) rank, when I user Value('avg') query 2 generate but all rank is 1 and when I use F('avg'), result is true but query 1 generate which is not optimal and calculate 'avg' twice(twice AVG(point) in query). -
Showing data in modal
Using Django 3 i developed a page where some tasks are showed like links. If task is not finished, than the user own can edit it, but if task is finished the user can only see. The tasks color are diferents from each task depends in the status: Atrasada, em dia, futura. The purpose is click in a task and open a modal with data from that task, but i dont know how to transfer data from main page to modal. I have no idea what to do. There is a way to make this using just django??? -
Django Rest Framework no read multiple records
I have tried everything on the blogs. I even consume the service with postman and multiple records are not inserted. Can you help me understand what is happening? There are no errors thrown by the code. Only one record is inserted. My code in DJANGO class ProviderListSerializer(serializers.ListSerializer): def do_stuff(data): return data def create(self, validated_data): some_data = self.do_stuff() return Provider.objects.bulk_create(some_data, ignore_conflicts=True) class ProviderSerializer(serializers.ModelSerializer): class Meta: model = Provider fields = '__all__' list_serializer_class = ProviderListSerializer class ProviderViewSet(viewsets.ModelViewSet): queryset = Provider.objects.all() serializer_class = ProviderSerializer def create(self, request, *args, **kwargs): many = isinstance(request.data, list) serializer = self.get_serializer(data=request.data, many=many) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, headers=headers) My code in POSTMAN: curl --location --request POST 'http://127.0.0.1:8000/api-auth/providers/' \ --header 'Authorization: Basic YRtaW46SklFTTkzMDYMQ==' \ --form 'name="Proveedor09"' \ --form 'representante="Proveedor09"' \ --form 'alias="Proveedor09"' \ --form 'ruc="isuioasuio92"' \ --form 'mobile="48489948"' \ --form 'address="shds"' \ --form 'telefono="45546546654"' \ --form 'email="Proveedor09@mail.com"' \ --form 'activo="true"' \ --form 'name="Proveedor091"' \ --form 'representante="Proveedor091"' \ --form 'alias="Proveedor091"' \ --form 'ruc="isuioasuio921"' \ --form 'mobile="48489948"' \ --form 'address="shds"' \ --form 'telefono="45546546654"' \ --form 'email="Proveedor109@mail.com"' \ --form 'activo="true"' I just expect to insert multiple records. As I said, I've tried everything I've seen on the web. Maybe I'm sending the form-data wrong, but I see that in many … -
Sync to Async Django ORM queryset foreign key property
Very simple question: Django. Model. Has foreign key: class Invite(models.Model): inviter = models.ForeignKey(User, on_delete=models.CASCADE, related_name='inviter') ... In async context, I do: # get invite with sync_to_async decorator, then print(invite.inviter) Get async favorite error: You cannot call this from an async context - use a thread or sync_to_async How do I handle this? -
Django retrieving data from m2m table
I am using Django default User model. I've made a relation m2m to it with model Books. Django made automaticly table in library app - library_books_user. How can I get acces to it? I want to be able to delete relations. Normally when I use not built in models i can do it like: models.BooksUsers.objects.get(book=book, user=user) importing models before. -
Not working Create Mutation in Graphql [django]
I use Django and graphql. Not working Create Mutation in Graphql. I can't understand why. Update and Delete works. But I can't create anything. class MovieCreateMutation(graphene.Mutation): class Arguments: title = graphene.String(required=True) year = graphene.Int(required=True) movie = graphene.Field(MovieType) def mutate(self, info, title, year): movie = Movie.objects.create(title=title, year=year) return MovieCreateMutation(movie=movie) and I have: class Query(api.schema.Query, graphene.ObjectType): pass class Mutation(api.schema.Mutation, graphene.ObjectType): pass schema = graphene.Schema(query=Query, mutation=Mutation) I'll say it again - Update and Delete mutations work. Only Create does not work. And I can't understand why. What I'm doing: mutation { createMovie(title: "TestMovie", year: 1981) { movie { title year } } } What do I always get: { "data": { "createMovie": { "movie": null } } } -
how to customize UserCreationForm in django
Hi I am trying to clean up my usercreation form using widgets but its not working. The class is not being passed 'form-control' It does however work for model form. Not sure what I am doing wrong? I am new. forms.py class ProfileForm(UserCreationForm): class Meta: model=User fields = ('email', 'avatar', 'password1', 'password2') def __init__(self, *args, **kwargs): super(ProfileForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' class CustomerForm(ModelForm): class Meta: model = Customer fields = ['name','email','phone_number' ] widgets={ 'name' :forms.TextInput(attrs={'class':'form-control'}), 'email' :forms.TextInput(attrs={'class':'form-control'}), 'phone_number' :forms.TextInput(attrs={'class':'form-control'}), } -
Django count records with aggregate
I have field like this I want all records count with all tags for example sale = Sale.objects.using('read_rep') \ .filter(tags__name__in=['Device','Mobile']) \ .aggregate( **{total: Count('pk', for status, _ in ['Device','Mobile']} ) Device - 2 Mobile-5 It is difficult to count records with all tags because tags are being store in only one field. Any help would be Appreciated. -
Group by field in serializer for DRF
I am trying to group all my articles by category for DRF. I have the following my serializers.py: class GroupPageSerializer(serializers.ModelSerializer): sound = serializers.FileField(required=False) image = Base64ImageField(max_length=None, use_url=True) category = serializers.PrimaryKeyRelatedField( many=True, queryset=Category.objects.all()) url = serializers.CharField(allow_null=True, required=False, default=None, allow_blank=True) english = serializers.CharField(source="base", required=False, allow_blank=True) per_language = PerLanguageCondensedSerializer(many=True, required=False, read_only=True) target = serializers.CharField(required=False, allow_null=True, allow_blank=True) base = serializers.CharField(required=False) class Meta: model = Page fields = ['per_language', 'base', 'target', 'english', 'date', "json", "id", "category", "title", "image", "sound", "url", "slug"] And this in my views.py: class GroupedArticleListView(generics.ListAPIView): queryset = Page.objects.select_related().all() serializer_class = GroupPageSerializer filter_backends = (filters.DjangoFilterBackend, OrderingFilter) pagination_class = LimitOffsetPagination ordering_fields = ['date'] filter_class = ArticleMultiValue I have been trying writing a list serializer class, I've been trying to write various "to_representation" functions, etc. All I want is so that all of my results are grouped by category, as such: "business": [ {article1...}, {article2...} ], "technology": [ {article3...}, {article8...}, ], etc How do I do this? -
How to change the docker and nginx config to support asgi WebSocket wss in Django?
I'm working on a small Django project related to a chat where I have to use WebSocket for real0time cominucation, I deployed my project using wsgi and it was working but when i reached the point of using websockt I found myself that I have to change the configuration to asgi or something, could you please help me out This is my project architecture: -myproject -docker(folder) -certbot(folder) -proxy(folder) -nginx (folder) -default-ssl.conf.tpl -uwsgi_params -Dockerfile (file2) -Dockerfile (file1) -Docker-compose-delpoy.yml This is my Dockerfile (file1) FROM python:3.10-alpine3.16 ENV PYTHONUNBUFFERED 1 COPY requirements.txt /requirements.txt RUN apk add --upgrade --no-cache build-base linux-headers && \ pip install --upgrade pip && \ pip install -r /requirements.txt COPY app/ /app WORKDIR /app RUN adduser --disabled-password --no-create-home django USER django CMD ["uwsgi", "--socket", ":9000", "--workers", "4", "--master", "--enable-threads", "--module", "myproject.wsgi"] This is my production Docker-compose-delpoy.yml version: '3.9' services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data - ./init.sql:/docker-entrypoint-initdb.d/init.sql environment: - POSTGRES_DB=xxx - POSTGRES_USER=xxx - POSTGRES_PASSWORD=xx app: build: context: . restart: always volumes: - .:/app environment: - DJANGO_DEBUG=0 - POSTGRES_NAME=xxx - POSTGRES_USER=xxx - POSTGRES_PASSWORD=xxx - DJANGO_SECRET_KEY=${DJANGO_SECRET_KEY} - DJANGO_ALLOWED_HOSTS=${DOMAIN} depends_on: - db redis: image: redis:alpine proxy: build: context: ./docker/proxy restart: always depends_on: - app ports: - 80:80 - 443:443 volumes: - certbot-web:/vol/www - … -
How to get same search result if i filter a value with hyphen or without hyphen or with white spaces in queryset field?
I need to get the same result when i search a word with or without a hyphen as well as white space in django queryset field.What should i do to satisfy this. -
Logging incorrect translations in Django
I often run into the mistake of using gettext in a context where the actual language is not set yet - instead of using the appropriate gettext_lazy. Those errors can be difficult to catch - I would like to make them more visible appropriate logging, or possibly even throwing exceptions. Would it be correct, to write a wrapper function that logs an error in the case of get_language() is None? Then of course, one would need to enforce that this wrapper is always used - introducing another subtle easy to make mistake. In general, I suppose monkey-patching could be used, but I'd like to avoid that if possible. The whole dispatch behind django.util.translation seems already relatively complex. Is there a clean way too hook this functionality in there? -
Django REST Framework caching programmatically
From the official docs it looks like the only way of caching with DRF is to use decorators. As far as I know, there is also a more flexible way to use caching directly querying the cache, like in the example below (source): from django.core.cache import cache from django.conf import settings from django.core.cache.backends.base import DEFAULT_TIMEOUT CACHE_TTL = getattr(settings, 'CACHE_TTL', DEFAULT_TIMEOUT) def cached_sample(request): if 'sample' in cache: json = cache.get('sample') return JsonResponse(json, safe=False) else: objs = SampleModel.objects.all() json = serializers.serialize('json', objs) # store data in cache cache.set('sample', json, timeout=CACHE_TTL) return JsonResponse(json, safe=False) This approach gives use more control over what and how long we store in the cache. So, my question is the following: is there a way to adapt this way of caching to a simple view defined in DRF? Example: # MODEL class Item(models.Model): code = models.CharField(max_length=8, primary_key=True) name = models.CharField(max_length=32) # SERIALIZER class ItemSerializer(serializers.ModelSerializer): class Meta: model = Pair fields = '__all__' # VIEW class ItemsList(generics.ListAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer def list(self, request): queryset = self.get_queryset() serializer = ItemSerializer(queryset, many=True) return Response(serializer.data) -
Django Rest Framework - overriding save in backend is not created custom id
I am working on a project. I have Django for my backend and Vue for my front end. When using the templates and saving in the Django project I have no issues. However, when I POST to my projects API the following save from my modal is not being created. models.py class DevProjects(models.Model): PROJECT_TYPE = [ ('New Application', 'New Application'), ('Update Application', 'Update Application'), ('Bug Fixes', 'Bug Fixes') ] PROJECT_STATUS = [ ('New', 'New'), ('In Progress', 'In Progress'), ('Complete', 'Complete'), ] project_id = models.CharField(max_length=15, editable=False, unique=True) project_title = models.CharField(max_length=100) project_desc = models.CharField(max_length=500) project_category = models.CharField(max_length=25, choices=PROJECT_TYPE, null=True, blank=True) project_status = models.CharField(max_length=25, choices=PROJECT_STATUS, default='New') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateField(auto_now=True) created_by = models.ForeignKey(User, related_name='projects', on_delete=models.CASCADE) def save(self, *args, **kwargs): super(DevProjects, self).save(**kwargs) self.project_id = 'PROJ-' + str(self.id) super(DevProjects, self).save(**kwargs) def __str__(self): return self.project_title I have the project_id being created on save which gets the original ID but just adds 'PROJ-' in front. Whenever I submit the form from my frontend, that save definition is not being called, thus not creating the project_id. Project ID is what I use to send a GET request to get the projects. serailizer.py class DevProjectSerializer(serializers.ModelSerializer): class Meta: model = DevProjects fields = ("project_id", "project_title", "project_desc", "project_category", "project_status") … -
How do I use Django generic updateviews to update my model using individual form field values?
models.py: from django.db import models class Location(models.Model): name = models.CharField(max_length=20) is_source = models.BooleanField(default=False) is_destination = models.BooleanField(default=False) def __str__(self): return self.name views.py from django.shortcuts import render from django.urls import reverse_lazy from django.views import generic from .models import Location class LocationsListView(generic.ListView): model = Location template_name = 'locations/list.html' context_object_name = 'locations' class LocationUpdateView(generic.edit.UpdateView): model = Location fields = ['name', 'is_source', 'is_destination'] context_object_name = 'location' template_name = 'locations/update.html' success_url = reverse_lazy('locations:list') class LocationDeleteView (generic.edit.DeleteView): model = Location template_name = 'locations/confirm_delete.html' context_object_name = 'location' success_url = reverse_lazy('locations:list') locations/update.html {% extends 'base.html' %} {% block title %}Location Update{% endblock %} {% block content %} <section> <div class="container"> <h1>Location Update</h1> <div class="form-container"> <form method="post"> {% csrf_token %} {% if form.errors %} <div class="p-3 mb-3 border border-danger border-3 rounded">{{ form.errors }}</div> {% endif %} <div class="mb-3"> <label for="" class="form-label">Name</label> <input type="text" class="form-control" value="{{ form.name.value }}"> </div> <div class="mb-3"> <input type="checkbox" class="form-check-input" {% if form.is_source.value %} checked {% endif %}> <label for="">Source</label> </div> <div class="mb-3"> <input type="checkbox" class="form-check-input" {% if form.is_destination.value %} checked {% endif %}> <label for="">Destination</label> </div> <input type="submit" class="btn btn-success mb-3" value="Save"> </form> </div> </div> </section> {% endblock %} locations.urls.py from django.urls import path from . import views app_name = 'locations' urlpatterns = [ path('', views.LocationsListView.as_view(), … -
django app - django.core.exceptions.ImproperlyConfigured
So I'd like to overwrite some of the signals provided by django all auth. Therefore I overwrite the core/apps.py file like this: class CoreAppConfig(AppConfig): name = 'core.apps.CoreAppConfig' label = "core" def ready(self): from allauth.account.signals import email_confirmed from allauth.account.models import EmailAddress from .signals import profile # todo import not working email_confirmed.connect(profile, EmailAddress) And my init file: default_app_config = 'core.apps.CoreAppConfig' And my installed apps include: 'core.apps.CoreAppConfig', "profile" is a signal which just creates a new Profile object for the user in the request. This is not the problem here. The problem is that when I run the server, an error occurs; Error: django.core.exceptions.ImproperlyConfigured: Cannot import 'core.apps.CoreAppConfig'. Check that 'core.apps.CoreAppConfig.name' is correct. -
Issues importing Chart.js into django project via CDN
I have a simple django project that needs the use of the Chart.js library for one of the templates. My base.html where I imported the library is shown below is shown below: <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]> <html class="no-js"> <!--<![endif]--> <html> <head> <style> body {font-family: Helvetica, Roboto, Georgia} div * {display:flex; justify-content:center} </style> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Switch Monitor</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href=""> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script type="module" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.0.1/chart.min.js" integrity="sha512-tQYZBKe34uzoeOjY9jr3MX7R/mo7n25vnqbnrkskGr4D6YOoPYSpyafUAzQVjV6xAozAqUFIEFsCO4z8mnVBXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> </head> <body> <div id="dialog" style="display:grid;justify-content:center"> {% block title %} <h1>Switch Monitor</h1> {% endblock title %} {% block content %} {% endblock content %} </div> {% block script %} <script src="" async defer></script> {% endblock script %} </body> </html> My django settings.py is shown below, the server was restarted after the CORS settings were changed. from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = … -
Django REST: Set all Serializer fields as not required at once
Is there any way to set my serializer fields as not required by default? it'll take me hours to set every field of every serializer I have as not required so I wanted to know if there's any shortcut. One example: class ComputersSerializer(serializers.ModelSerializer): name = serializers.CharField(required=False) serial = serializers.CharField(required=False) otherserial = serializers.CharField(required=False) contact = serializers.CharField(required=False) contact_num = serializers.CharField(required=False) comment = serializers.CharField(required=False) date_mod = serializers.DateTimeField(required=False) is_template = serializers.IntegerField(default=0) template_name = serializers.CharField(required=False) is_deleted = serializers.IntegerField(default=0) is_dynamic = serializers.IntegerField(default=0) ticket_tco = serializers.DecimalField(max_digits=20, decimal_places=4, required=False) uuid = serializers.CharField(required=False) date_creation = serializers.DateTimeField(required=False) is_recursive = serializers.IntegerField(default=0) last_inventory_update = serializers.DateTimeField(required=False) computertypes = ComputertypesSerializer(required=False) computermodels = ComputermodelsSerializer(required=False) entities = EntitiesSerializer(required=False) networks = NetworksSerializer(required=False) locations = LocationsSerializer(required=False) autoupdatesystems = AutoupdatesystemsSerializer(required=False) users = assistanceSerializers.UsersSerializer(required=False) groups = assistanceSerializers.GroupsSerializer(required=False) states = StatesSerializer(required=False) users_tech = assistanceSerializers.UsersSerializer(required=False) groups_tech = assistanceSerializers.GroupsSerializer(required=False) manufacturers = ManufacturersSerializer(required=False) class Meta: model = Computers fields = '__all__' For the moment I had to set it for each field. I've been searching if someone had the same problem but it looks like I'm lazier than the rest of programmers. -
<embed> - src from proxy server
I am currently struggling with setting the src attribute of the <embed> element. I have my PDF documents stored in the cloud storage with limited access. My application has users, and each user has its own set of PDF contracts on the dedicated namespace. Since I do not want to expose any URL to the users nor call the storage from the front end, I prepared a proxy endpoint (with authorized access) that returns the application/pdf response to be displayed in a particular <embed> component. Does anyone know how to display the content with this paradigm? Thank you for any hint. -
use of gTTS in Django project
i want to use gTTS in my Django project. Accordingly i installed django-gtts(pip install Django-Gtts). It is installed successfully.. later i added 'gTTS' under INSTALLED-APPS of setting.py file. Then run the server and also tried makemigrations gTTS. in both the case got below errir. import_module(entry) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in imp ort_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'gTTS' please suggest what i should next.. i tried all possible way with my litte knowledge but unable to fix it.. please let me know if you need more information. -
Group by in serializer in Django Rest Framework
I am new to Django Rest Framework, I want to group my serializer data by date, How can I do that. How can I group this by Date? my model: mongo model with some more fields also but only uses these two fields class Activity(Document): """ mongo model """ candidate_id = StringField(required=True, db_field='c') timestamp = DateTimeField(required=True, db_field='d') ... ... more fields My Views: my views file class RecentActionView(generics.ListAPIView): serializer_class = RecentActionSerializer def get_queryset(self): recruiter_id = self.request.GET.get("recruiter_id") activity_list = Activity.objects.filter(recruiter_id=str(recruiter_id)).order_by('- timestamp') return activity_list my serializer: using serializermethod field to get data from other DB by using candidate id from activity model class RecentActionSerializer(serializers.Serializer): name = serializers.SerializerMethodField() designation = serializers.SerializerMethodField() age = serializers.SerializerMethodField() timestamp = serializers.DateTimeField(format="%H:%M") def get_name(self, obj): return something def get_designation(self, obj): return something def get_age(self, obj): return something I want to group my response by Date like : [ { "date": "2022-12-05", "candidates":[ { "name": "One", "designation": "Lead", "age": 30, "timestamp": "14:30" } ] }, { "date": "2022-12-04", "candidates":[ { "name": "Two", "designation": "Lead", "age": 30, "timestamp": "14:30", } ] } ] my actual response is like: [ { "name": "One", "designation": "Lead", "age": 30, "activity_timestamp": "13:12" }, { "name": "Two", "designation": "Lead", "age": 30, "activity_timestamp": "13:12" } ] -
Fetch Python Logger Formatter Variables in Code
I have a Django project and this is what the logger formatter configuration looks like. 'formatters': { 'simple': { 'format': '%(asctime)s SCORPIO [%(request_id)s] ' + os.environ['ENVIRONMENT'] + ': %(message)s', 'datefmt': '%Y-%m-%dT%H:%M:%S', }, }, How does Python pick the different variables (asctime, request_id) provided in the format? I need to fetch the request_id variable in case of a failure and display it on a page. I've mostly worked with Java in which these variables are picked from the ThreadContext so I tried looking for such an alternative in Python but couldn't find one.