Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to query the existence of related objects that are successive in time?
My Blog model has a has two types of comments, blue ones and red ones. I would like to find all blogs that have posts that are blue directly followed by posts that are red. Here, "followed by" is meant in terms of a timestamp field "created_at". How can I filter my blogs by this property? class Comment(Model): color = Charfield(max_length=100) created_at = DateTimeField() blog = ForeignKey(Blog, related_name="comments") class Blog(Model): ... My attempt is: blue_comments = Comment.objects.filter(blog=OuterRef("pk"), color="blue") red_comments = Comment.objects.filter(blog=OuterRef("pk"), color="red") blogs = Blog.objects.filter(Exists(blue_comments), Exists(red_comments)).all() I don't know how to filter for the condition that the "created_at" fields must be successive. -
Add properties to a model from a different app in django? (extend model from different app)
I've got an app (named essence) that I use in multiple projects (it's a shared app with just a User model and a Location model that get used in multiple projects I have) The Location model looks something like this: class Location(models.Model): name = models.CharField(max_length=50) alternate_location_id = models.IntegerField() class Meta(object): ordering = ["name"] def __str__(self): return self.name Currently I have a function that takes a queryset of locations, iterates across it and creates a dictionary for each location with the needed data. But that is causing a lot of extra queries I'd like to avoid. So I'm trying to see if I can dynamically add properties to the Location model from the positions app. The function returns a dictionary that looks like this: { "location_id": location.id, "location_name": location.name, "alternate_location_id": location.alternate_location_id, "location_current_position_count": position_count, "location_current_position_average": position_average, "location_change": location_position_change, } The three variables listed in that dictionary (position_count, position_average and location_position_change) are figured out using various queries of other related models in the function (which are not using aggregate/annotate, but could/should be - hence my refactoring now) I would like to get rid of that function and just make those other variables attributes/properties on the Location model itself so I'm not having to … -
SQL - How to get rows within a date period that are within another date period?
I have the following table in the DDBB: On the other side, i have an interface with an start and end filter parameters. So i want to understand how to query the table to only get the data from the table which period are within the values introduces by the user. i.e If the users only defines start = 03/01/2021, then the expected output should be rows with id 3,5 and 6. if the users only defines end = 03/01/2021, then the expected output shoud be rows with id 1 and 2. if the users defines start =03/01/2021 and end=05/01/2021 then the expected output should be rows with id 3 and 5. Hope that makes sense. Thanks -
Use different models for user and superuser in django
I have a Student model and I will also be creating another model called Teacher. But I want a single model called Admin to be the superuser for both of these models in their respective managers. How do I achieve this? Here's the code I have so far: class StudentManager(BaseUserManager): def create_user(self, usn, email, first_name, last_name, initials, branch, **extra_fields): if not email: raise ValueError('Email for user must be set.') email = self.normalize_email(email) user = self.model( usn=usn, email=email, first_name=first_name, last_name=last_name, initials=initials, branch=branch, **extra_fields) user.set_password('password') user.save() return user def create_superuser(self, name, email, **extra_fields): if not email: raise ValueError('Email for user must be set.') email = self.normalize_email(email) admin = self.model( # but self.model refers to Student, not Admin email=email, name=name, **extra_fields) admin.set_password('password') admin.save() return admin class Student(AbstractBaseUser, PermissionsMixin): usn = models.CharField(max_length=10, primary_key=True, unique=True, editable=False) email = models.EmailField(max_length=254, unique=True) first_name = models.CharField(max_length=50, null=False) last_name = models.CharField(max_length=50, null=False) initials = models.CharField(max_length=10, null=True) branch = models.CharField(max_length=5, null=False, editable=False) objects = StudentManager() USERNAME_FIELD = 'usn' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['email', 'first_name', 'last_name', 'branch'] class Admin(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=100, null=False) # objects = StudentManager() USERNAME_FIELD = 'name' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['email', 'name'] And here's the error I get: api.Admin.groups: (fields.E304) … -
Sorting and filtering django model objects by foreign key values
so i was given a test for an interview and trying to figure out the best way to implement this: Lets say we have a django project. With models: Rental name Reservation rental_id checkin(date) checkout(date) Add the view with the table of Reservations with "previous reservation ID". Previous reservation is a reservation that is before the current one into same rental. so i tried implementing something that actually works, but i just feel i have ignored alot of good practices just to get the work done, I will appreciate some insights/tips on how i can improve my code, thanks guys. Ps: i really need the job :( Here is a sample of my code: ##### models from django.db import models # Create your models here. class Rental(models.Model): name = models.CharField(max_length=100) def __str__(self) -> str: return self.name class Reservations(models.Model): rental_id = models.ForeignKey(Rental, related_name="rental_id", on_delete=models.CASCADE) checkin = models.DateField() checkout = models.DateField() def __str__(self) -> str: return f"{self.rental_id.name}, {self.id}" #### The views implementation from django.shortcuts import render from .models import Rental, Reservations def All_Reservation(request): reservations = Reservations.objects.all() rental_names = Rental.objects.values_list('name') ValueSet = [] for i in sort_by_rental_name(rental_names): ValueSet += i mapped = zip(ValueSet,reservations) print(dict(mapped)) context = { 'reservations': reservations, 'values': ValueSet } return … -
Number of occurrences in django
How to calculate and save in database the number of occurrences per day of the number of participants lower than the maximum number of participants in a space of radius R=50km. # models.py class Even(models.Model): name = models.CharField(max_length=200, null=True, blank=True) date = models.DateField(null=True, blank=True) time = models.TimeField(null=True, blank=True) participant = models.PositiveIntegerField(null=True, blank=True) longitude = models.FloatField(null=True, blank=True) latitude = models.FloatField(null=True, blank=True) geom = models.PointField(srid=4326, null=True, blank=True,) @property def longitude(self): return self.geom.x @property def latitude(self): return self.geom.y def __str__(self): return self.name # views.py def even_nb_jour(request): labels = [] data = [] today = date.today() even_max_today = Even.objects.filter(date=today).aggregate(Max('particpant')) pnt = Even.objects.filter(date=today).filter(geom_magnitude=even_max_today) queryset = Even.objects.filter(date=today).values('time').filter(geom__distance_lte=(pnt, Distance(km=50))).annotate(time_name=Count('name')).order_by('time') for rm in queryset: labels.append(rm['time']) data.append(rm['time_name']) return JsonResponse(data={ 'labels': labels, 'data': data, }) -
How to nest Some of the UserModel fields into another Serializer
I have a model name Comment as follows. class Comment(models.Model): message = models.CharField(max_length=1000) time = models.DateTimeField(auto_now_add=True) sender = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='usercomment') def __str__(self): return self.sender.name For this model, I have a serializer class CommentSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) time = serializers.DateTimeField(read_only=True) message = serializers.CharField(read_only=True) sender = serializers.PrimaryKeyRelatedField(read_only=True, many=False) name = serializers.StringRelatedField( source='sender', read_only=True, many=False) I have another serializer for the sender information that is linked with Forignkey to AUTH_USER_MODEL, and for that Part, I have another serializer to nest some of the fields from the User model. class SenderInformation(serializers.Serializer): id = serializers.UUIDField(read_only=True) name = serializers.CharField(read_only=True) avatar = serializers.ImageField(read_only=True) And the main objective is to Nest this SenderInformation into CommentSerializer. How can I achieve this? -
How to pass unique objects from a second model in ListView function to the template django
I am creating a blog app in django. For that, I have made a page where all available blogs are listed. I am using generic.ListView view to achieve this. But, I also want to create a writer's section where I can list some details about the writers that have written those blogs. For this, I need to get all the users that have written a blog and then find distinct users from that and list out their username. I have an author field in my Blog model that keeps track of the writer user. How can I get the distinct usernames of these writers and pass it into my template? Models.py: class Blog(models.Model): blog_head = models.CharField(max_length=100) blog_header_image = models.ImageField(upload_to="photos/blogs/", null=True, blank=True) #blog_content = models.TextField() blog_content = RichTextField(blank=True, null=True) #blog_summary = models.TextField(max_length=355) blog_summary = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) blog_date = models.DateField(auto_now_add=True) likes = models.ManyToManyField(User, related_name='blog_post_likes', blank=True) def __str__(self): return self.blog_head def get_absolute_url(self): return reverse('blog-full', args=[str(self.id)]) def blog_likes_count(self): return self.likes.count() Views.py: class blogs_getting_Listview(ListView): model = Blog template_name = 'blogs.html' ordering = ["-blog_date"] def get_context_data(self, *args, **kwargs): context = super(blogs_getting_Listview, self).get_context_data() authors_id_list = Blog.objects.get(id=id).author authors_list = "" for author_in in authors_id_list: author_obj = User.objects.get(id=author_id) authors_list = authors_list + author_obj context.update({ "authors_list": authors_list … -
Send full image url in DRF
I am trying to get the full image URL in the API in DRF i am trying to use build_absolute_uri but i keep receiving the error The 'image' attribute has no file associated with it. the serializer.py: class VesselInfoSerializer(serializers.ModelSerializer): image_url = serializers.SerializerMethodField() def get_image_url(self, Vessel): request = self.context.get('request') image_url = Vessel.image.url return request.build_absolute_uri(image_url) vessel_component_count = serializers.IntegerField( source='vessel_components.count', read_only=True ) vessel_inventory_category_count = serializers.IntegerField( source='vessel_inventory_category.count', read_only=True ) vessel_inventory_item_count = serializers.IntegerField( source='category_items.count', read_only=True ) class Meta: model = Vessel fields = '__all__' models.py: class Vessel(models.Model): name = models.CharField(max_length=255) imo = models.CharField(max_length=255) image = models.ImageField(blank=True, upload_to='vessel_image') def __str__(self): return self.name the view: @api_view(['GET']) def getVesselInfo(request): vessels = Vessel.objects.all() vSerializer = VesselInfoSerializer( vessels, many=True, context={"request": request}) return Response(vSerializer.data) -
The CSV script in Django does not see the d path of the file - [Errno 2] No such file or directory
Why is my Pytnon/Django script unable to read the file path and retur. How to correctly set the path from a saved file? [Errno 2] No such file or directory: '/media/file_hll8NoJ.csv Views.py if form.is_valid(): cd = form.cleaned_data if cd['file']: obj = FileUpload() obj.file = cd['file'] obj.save() with open(obj.file.url) as f: reader = csv.reader(f) for row in reader: _, created = UserEmail.objects.get_or_create( owner=obj_instance, email=row[0], middle_name=row[2], ) Path is correct and if I open http://127.0.0.1:8000/'/media/file_hll8NoJ.csv loacal all works fine (I can see my csv file) -
How to list overdue objects?
I want to create a query that shows which user has how many overdue (out of date) missions. query_overdue = Case.objects.select_related('last_changed_by').values('due_date').order_by('assigned_to').annotate( name=F('assigned'), due=F('due_date'), ) This query shows every object but I want to filter it with not none value and overdue. How can I do it? -
İ can't pull data with JavaScript
I want to pull data using JavaScript and show it in console. I don't know what I did wrong. main.js // ADD TO CART $("#addToCartBtn").on('click',function(){ var _qty=$("#productQty").val(); var _productId=$(".product-id").val(); var _productName=$(".product-name").val(); console.log(_productId,_productName,_qty); }); I am using django framework to write backend detail.html <div class="product-btns"> <div class="qty-input"> <span class="text-uppercase">Ədəd: </span> <input class="input" type="number" value="1" id="productQty"> </div> <input type="hidden" class="product-id" value="{{product.id}}"> <input type="hidden" class="product-name" value="{{product.name}}"> <button class="primary-btn add-to-cart"><i class="fa fa-shopping-cart" id="addToCartBtn"></i> Səbətə at</button> </div> -
Session information is not stored in the database(django-session table)-I have used a custom model and backend
i use multiple backend and model for user authentication the default django auth system and m I use multiple backend and models for user authentication Default Django's model and a customized one . Default django authentication for admin-users and customized model and backend for customer-users Now The problem is when customer-users login their session information does not stored in the database(django-session table),so Because their sessions are not saved, they need to re-login each time the page is refreshed or changed -
Please help me fixing out my django chained dropdown
I am having issues with chained dropdown can someone help me fixing it out.I have created both category and sub category model, product model, html pages, views and everything neccessary to make this code work but it's not working now.it was working when before but now the same code is not working i have no idea what happened to it.I took this code from a youtube tutorials i guess that's the reason i am having trouble fixing it out. forms.py ``` class AdminProductForm(forms.ModelForm): user = forms.ModelChoiceField(label="", queryset=User.objects.all(), widget=forms.HiddenInput(), required=False) image = forms.FileField(label='Thumbnail', widget=forms.FileInput( attrs={'class': 'form-control'}), required=False) class Meta: model = AdminProduct fields = ['user', 'title', 'details', 'image', 'sp', 'dp', 'download_link', 'preview_link','category', 'subcategory', 'tags'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['subcategory'].queryset = AdminSubCategory.objects.none() if 'category' in self.data: try: category_id = int(self.data.get('category')) self.fields['subcategory'].queryset = AdminSubCategory.objects.filter(category_id=category_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['subcategory'].queryset = self.instance.category.subcategory_set.order_by('name') models.py class AdminCategory(models.Model): name = models.CharField(max_length=50) def __str__(self) -> str: return self.name class AdminSubCategory(models.Model): category = models.ForeignKey(AdminCategory, on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self) -> str: return self.name class AdminProduct(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=150) details = RichTextField() image = models.ImageField(upload_to="AdminProduct_Images/") download_link = … -
Add custom formatter tags in papertrail Logger in django
settings Page: "formatters": { "simple": { "format": "%(name)s %(asctime)s %(message)s", "datefmt": "%Y-%m-%dT%H:%M:%S", }, }, If I write here code like this: "formatters": { "simple": { "format": "%(name)s %(ip)s %(user)s %(client)s %(asctime)s %(message)s", "datefmt": "%Y-%m-%dT%H:%M:%S", }, }, It is showing following Error: --- Logging error --- Traceback (most recent call last): File "C:\Program Files\Python10\lib\logging\__init__.py", line 440, in format return self._format(record) File "C:\Program Files\Python10\lib\logging\__init__.py", line 436, in _format return self._fmt % values KeyError: 'ip' -
How to use Django with Docker and have no problems with migrations?
During working with docker where I dockerised Django PostgreSQL, I've entered in such problems as when I change some model and migrate it, after entering to the page, it says there is no such relationship in the database. After some research, I found that problem can be due to creating every time new migration and deleting the old. How can I fix this problem? Below you can see my configurations docker-compose-prod.yml services: app: volumes: - static_data:/app/staticfiles - media_data:/app/mediafiles env_file: - django.env - words_az.env - words_en.env build: context: . ports: - "8000:8000" entrypoint: /app/script/entrypoint.sh command: sh -c "python manage.py collectstatic --no-input && gunicorn --workers=3 --bind 0.0.0.0:8000 django.wsgi:application" depends_on: - db nginx: build: ./nginx volumes: - static_data:/app/staticfiles - media_data:/app/mediafiles ports: - "80:80" - "443:443" depends_on: - app - flower db: image: postgres:14.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - db.env ports: - "5432:5432" redis: image: redis:alpine ports: - "6379:6379" worker: build: context: . command: celery -A django worker -l info env_file: - django.env depends_on: - db - redis - app flower: build: ./ command: celery -A django flower --basic_auth=$user:$password --address=0.0.0.0 --port=5555 --url-prefix=flower env_file: - django.env ports: - "5555:5555" depends_on: - redis - worker volumes: postgres_data: static_data: media_data: Dockerfile FROM python:3.9-alpine ENV PATH = "/script:${PATH}" … -
Is it possible to add more than one field to Meta in Model?
I´m trying to add a unique together to my model, in which I have assigned permissions for backend roles. My model is like this: class Detail(models.Model): order=models.ForeignKey('Order',related_name='orders',on_delete=models.CASCADE,verbose_name='Order') component=models.ForeignKey('Component', related_name='order_component',on_delete=models.RESTRICT,verbose_name='Component') class Meta: unique_together = ('order', 'component') permissions = (("detail_list", "detail_list"),) When I try to save, it just keep me saying this: IndentationError: unindent does not match any outer indentation level I guess I could add permissions in a latter Model, but just for curiosity, anybody please could tell me if that´s the best approach, or if there is somethig I am missing? Cheers -
Filter Django ForeignKey Dropdown based on Current User
I am using django ClassBasedViews where I have a Project and Task Models. Each task is assigned to a project and both models register who created a recording in the created_by field. class Project(models.Model): name = models.CharField(max_length=100) ... created_by = models.ForeignKey(User, on_delete=models.CASCADE) and then for the Tasks, I have class Task(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) task_name = models.CharField(max_length=200) ... created_by = models.ForeignKey(User, on_delete=models.CASCADE) So the ClassBasedView to create the new task is like so, class CreateTask(LoginRequiredMixin, CreateView): template_name = 'project/new _task.html' form_class = TaskCreationForm success_message = "New Task Created" I need the dropdown in the form to Only show projects for the current logged-in user. I have gone through this post but the author did not implement my use case for *the current logged-in user. What can I do and how can I implement this? -
Django: form and list of nested objects
I can't make an object list, which itself will restrict the following object list. Let me explain: I have a model Base with a foreignkey field, referring to a model Parent1 which itself refers a foreignkey to a model Parent2. I would like to make a form where we choose the Parent2, then the Parent1 with a choice delimited by the Parent2. class Parent2(models.Model): title = models.fields.CharField(max_length=100) def __str__(self): return f'{self.title}' class Parent1(models.Model): title = models.fields.CharField(max_length=100) parent2 = models.ForeignKey(Parent2, null=True, on_delete=models.SET_NULL) def __str__(self): return f'{self.title}' class Base(models.Model): title = models.fields.CharField(max_length=100) parent1 = models.ForeignKey(Parent1, null=True, on_delete=models.SET_NULL) def __str__(self): return f'{self.title}' def base_registration(request): base_form = forms.BaseForm() if request.method == 'POST': base_form = forms.BaseForm(request.POST) if all([document_form.is_valid()]): base = base_form.save(commit=False) base.save() context = { 'base_form': base_form, } return render(request, 'base_registration.html', context=context) class BaseForm(forms.ModelForm): title = forms.CharField(max_length=20, help_text="Title") parent1 = forms.ModelChoiceField(queryset=models.Parent1.objects.all(), required=False) parent2 = forms.ModelChoiceField(queryset=models.Parent2.objects.all(), required=False) class Meta: model = models.Base fields = ['parent2', 'parent1', 'title'] -
django search where database value is part equal to search value
value_in_database = 'Computer Solutions' search_value = 'Solutions' I know that if I have values like the above, I can find my object like this: model.objects.filter(name__icontains=search_value) But I was wondering if the opposite is possible in Django? value_in_database = 'Solutions' search_value = 'Computer Solutions' model.objects.filter(name=search_value) -
Django Serializer field validator not being called
Serializer field validator not being called seems to be a common problem but I cannot find the right solution. I have a normal (NON-MODEL) serializer with a URLField and a custom validator for the field. The field validator is not being hit when running is_valid(), instead the builtin URLValidator is being called. Here is the custom validator (only to avoid http:// not included error): class OptionalSchemeURLValidator(URLValidator): def __call__(self, value): if "://" not in value: value = "http://" + value super(OptionalSchemeURLValidator, self).__call__(value) Here is the serializer: from rest_framework.serializers import Serializer class DeveloperAccessTokenSerializer(Serializer): token = CharField(read_only=True) company_website = URLField( required=False, validators=[OptionalSchemeURLValidator()], ) def create(self, validated_data): self.token = jwt.encode( jwt_payload, settings.SECRET_KEY, algorithm="HS256" ) self.company_website = validated_data.get("company_website", None) return self.company_website Here is how the serializer is being used: def post(self, request, *args, **kwargs): context = {"request": request} ser = self.serializer_class(data=request.data, context=context) ser.is_valid(raise_exception=True) token = ser.save() return Response(token, status=HTTP_201_CREATED) Validation error is being raised on is_valid(): rest_framework.exceptions.ValidationError: {'company_website': [ErrorDetail(string='Enter a valid URL.', code='invalid')]} Input value for the field is www.my-website.com -
With Django, should we be writing functions inside views, or importing them from another python file?
When writing functions for views, should they be placed within the specific views, outside of the views within views.py or inside a separate script such as viewsfunctions.py? Is there any advantage/requirement for any of these options? As an example, if we were writing a function to convert units of weight from one to another for unified measurement, where should this function be written? -
Display (4.0) Django models.JSONFields as form in webpage
I am working on a Django based website. I have defined a JSONFields in my backend DB table , let's called it "CampaignTable" The JSONFields is used to store Campaign parameters which might differ from campaign to campaign. I want to collect campaign configuration from web user in a form , this form is actually transfer from JSONFields (key:value) to Form (fields:value) Is there a way to do it in Django or any plugins I can use ? -
Django Get username from filled login entry field
Need to log when user fails to login. Function: if request.user.is_authenticated: for g in request.user.groups.all(): list_aaa.append(g.name) logging.info('User ' + request.user.username + ' logged in (from IP: ' + request.META.get('REMOTE_ADDR') + ') ' + 'Group: ' + str(list_aaa)) else: logging.info('User ' + request.user.username + ' from IP: ' + request.META.get('REMOTE_ADDR') + ' failed to log in providing incorrect credentials') After successful login this function logs User xxxx logged in (from IP: 10.10.10.0) Group: ['AAA_ENGINEER', 'BBB_VPN_'] but when user login failed it returns: User from IP: 10.10.10.10 failed to log in providing incorrect credentials I have tried replacing request.user.username with request.META.get('USERNAME') and on my local machine + PyCharm this works but on development server request.META.get('USERNAME') returns None In debug i can see following query and in the end you can see user passed as arg, but how can i reach it: 2022-05-16 12:26:45 [DEBUG] (0.002) QUERY = 'SELECT TOP 21 [auth_user].[id], [auth_user].[password], [auth_user].[last_login], [auth_user].[is_superuser], [auth_user].[username], [auth_user].[first_name], [auth_user].[last_name], [auth_user].[email], [auth_user].[is_staff], [auth_user].[is_active], [auth_user].[date_joined] FROM [auth_user] WHERE [auth_user].[username] = %s' - PARAMS = ('xxxx',); args=('xxxx',) -
getting problem with working nested json in django framework
Hi Everyone I am trying to writing a code to get nested response based on driver_id, i am not able to solve this issue, kindly help me out. views.py def retrieve(self, request, *args, **kwargs): rating= connection.cursor() rating.execute(''' SELECT...... ''') rating_data=rating.fetchall() json_res=[] obj={} for row in rating_data: json_obj=dict(week_start_date=row[0],week_end_date=row[1],driver_id=row[2],driver_name=row[3],mobile=row[4],week_period=row[5],total_trips=row[6],driver_rating=row[7]) if obj.get('driver_id')==row[2]: obj['mobile'].append(json_obj) else: if obj.get('driver_id')!=None: json_res.append(obj) obj={} obj['driver_id']=row[2] obj['driver_name']=row[3] obj['mobile']=[json_obj] json_res.append(obj) return JsonResponse(json_res,safe=False) current response [{"driver_id": 10884, "driver_name": "Dipankar Mandal", "mobile": [{"week_start_date": "2022-05-09", "week_end_date": "2022-05-15", "driver_id": 10884, "driver_name": "Dipankar Mandal", "mobile": "8348447439", "week_period": "last week", "total_trips": 60, "driver_rating": "Mediocre"}]}, {"driver_id": 160, "driver_name": "Mohd Sohail Shaikh", "mobile": [{"week_start_date": "2022-04-18", "week_end_date": "2022-04-24", "driver_id": 160, "driver_name": "Mohd Sohail Shaikh", "mobile": "7718908984", "week_period": "4th week", "total_trips": 20, "driver_rating": "Mediocre"}, {"week_start_date": "2022-05-09", "week_end_date": "2022-05-15", "driver_id": 160, "driver_name": "Mohd Sohail Shaikh", "mobile": "7718908984", "week_period": "last week", "total_trips": 53, "driver_rating": "Mediocre"}]}, {"driver_id": 10884, "driver_name": "Dipankar Mandal", "mobile": [{"week_start_date": "2022-05-02", "week_end_date": "2022-05-08", "driver_id": 10884, "driver_name": "Dipankar Mandal", "mobile": "8348447439", "week_period": "2nd week", "total_trips": 60, "driver_rating": "Mediocre"}]}] expected output [{"driver_id": 10884, "driver_name": "Dipankar Mandal", "mobile": [{"week_start_date": "2022-05-09", "week_end_date": "2022-05-15", "driver_id": 10884, "driver_name": "Dipankar Mandal", "mobile": "8348447439", "week_period": "last week", "total_trips": 60, "driver_rating": "Mediocre"}, {"week_start_date": "2022-05-02", "week_end_date": "2022-05-08", "driver_id": 10884, "driver_name": "Dipankar Mandal", "mobile": "8348447439", "week_period": "2nd week", "total_trips": 60, "driver_rating": "Mediocre"}]}, …