Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to aggregate annotated related objects
How to calculate quantity_released from OrderedProduct? I cant just self.product_reservation.aggregate(total=Sum('quantity_released')) because you cant aggregate functions or even properties. I have tried extra and subqueries with annottation, but cant make it. class OrderProduct(models.Model): ... quantity_ordered = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) # TODO def quantity_released(self): return self.product_reservations.all() class ProductReservation(models.Model): ... order_product = models.ForeignKey("documents.OrderProduct", related_name='product_reservations' ,on_delete=models.CASCADE, blank=True, null=True) product_release = models.ManyToManyField("documents.ProductRelease", related_name='products_reservation', blank=True) def quantity_released(self): return self.product_release.all().aggregate(total=Sum('quantity'))['total'] class ProductRelease(models.Model): ... quantity = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) PS: If I have typed too inaccurate title then please edit it as I don't know how to phrase it better. Thank you. -
java-script programmatically created with Django seems to abbreviate itself
i have a js function written with django below function make_selected_func() { console.log("1111") clear_capcode() clear_derivs() clear_models() var make_selected = document.getElementById('makes').value console.log("@@@@@@") console.log(make_selected) var models_sel = document.getElementById('models') var unique_models = [] while (models_sel.options.length > 0) { models_sel.remove(0); } {% for car in cars %} if (! unique_models.includes('{{car.model}}')){ if ('{{car.make}}' == make_selected) { unique_models.push('{{car.model}}') } } etc.... when i go to my page the results i actually get in the html are... function make_selected_func() { console.log("1111") clear_capcode() clear_derivs() clear_models() var make_selected = document.getElementById('makes').value console.log("@@@@@@") console.log(make_selected) var models_sel = document.getElementById('models') var unique_models = [] while (models_sel.options.length > 0) { models_sel.remove(0); } if (! unique_models.includes('3 Series G20 Saloon')){ if ('BMW' == make_selected) { unique_models.push('3 Series G20 Saloon') } else{ } } if (! unique_models.includes('3 Series G20 Saloon')){ if ('BMW' == make_selected) { unique_models.push('3 Series G20 Saloon') } else{ } } if (! unique_models.includes('3 Series G20 Saloon')){ if ('BMW' == make_selected) { unique_models.push('3 Series G20 Saloon') } else{ } } if (! unique_models.includes('3 Series G20 Saloon')){ if ('BMW' == make_selected) { ……… ….. skipping thousands of lines ….. ……….. if ... == $0 below is the error i get. im guessing the js is so long it cant complete writing the function. it appears to … -
Django-wiki hit error when trying to access
enter image description here at the beginning, I executed Django run server after that I go to http://127.0.0.1:8000/ to try to access this wiki page are hitting error >> global flags not at the start of the expression at position 7 when i remove that line, it's works, but problems is if that line is removed, the content will gone I just started Django 1 week, please help to to overcome this error expect able to overcome this issue and launch the page successfully -
DRF social authentication
Im implementing drf social oauth2 and while accessing the URL - localhost:8000/auth/login/facebook/ I get 'drf' is not a registered namespace, No ReverseMatch error and when I change my namespace to social, I get 'social' is not a registered namespace. #URLPatterns urlpatterns = [ path("admin/", admin.site.urls), path('auth/', include('drf_social_oauth2.urls', namespace='social')), path('api/', include("users.urls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #Installed Apps INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", # rest "rest_framework", "corsheaders", "rest_framework_simplejwt", # Oauth "oauth2_provider", "social_django", "drf_social_oauth2", # apps "accounts", "inventory", "cart", "orders", "users", ] -
Get and insert bit in MySQL by input:radio
I need to insert a bit value in my MySQL, but I don't understand how. I use Django so I get the input value by employing = request.POST.get('employing') and I send by QuerySet(employing=employing) <input class="form-check-input" type="radio" name="employing" id="employingTrue" value="01" checked required /> I've tried value="1", value="b'1'", value="true", but I always got : (1406, "Data too long for column 'employing' at row 1") -
Django add constraint for foreign key fields to match
In Django I have a model that links a tenant to a facility (house). The tenant and the facility needs to be in the same site (city) for this link to be valid. To enforce this I want to add a constraint that checks if the tenant's site and the facility's site matches. I have tried to add a CheckConstraint to the model, but this compiles to a migration that is always false. Model: class TenantInFacility(models.Model): tenant = models.ForeignKey(Tenant, on_delete=models.DO_NOTHING) facility = models.ForeignKey(Facility, on_delete=models.DO_NOTHING) percentage_used = models.DecimalField(default=100, max_digits=6, decimal_places=3) start = models.DateTimeField(default=datetime.datetime.fromtimestamp(0)) end = models.DateTimeField(default=None, blank=True, null=True) class Meta: verbose_name_plural = "tenants in facilities" constraints = [ models.CheckConstraint(check=models.Q(models.F("tenant__site") == models.F("facility__site")), name='tenant_facility_sites_match') ] def __str__(self): return self.tenant.site.name + ": " + self.tenant.name + " in " + self.facility.name Migration: operations = [ migrations.AddConstraint( model_name='tenantinfacility', constraint=models.CheckConstraint(check=models.Q(False), name='tenant_facility_sites_match'), ), ] Is there a way in Django to require a foreign key's foreign key to match another foreign key's foreign key. In diagram form: +----------+ | Tenant | +----------+ / \ / \ +--------------------+ +------+ | Tenant in Facility | | Site | +--------------------+ +------+ \ / \ / +----------+ | Facility | +----------+ -
Django no access to certain methods AbstractUser using UserManager
I am new to Django I am trying to get access to form.save() using form = self.form_class(request.POST) but I have been having to use methods like self.get_form_class() to access form.is_valid() and form.save() but cannot get method set_password() from user = form.save(commit=False) I am not sure what the problem is. Why cant I access user.set_password()? Even when I try to create a BaseUserManager self.model() does not give me a definition for user.set_password() or user.save() why is this? # views.py class RegistrationView(CreateView): template_name = "AskQuestions/customuser_form.html" form_class = RegistrationForm model = CustomUser success_url = "questions/login" def get(self, request, *args, **kwargs): form = self.get_form_class() form = form(initial=self.initial) return render(request, self.template_name, {"form": form}) def post(self, request): form = self.get_form_class() form = form(request.POST) if (form.is_valid()): user = form.save(commit=False) # user.set_password() no definition user.set_password() messages.add_message(request, messages.SUCCESS, "Your account has been successfully created.") return redirect("AskQuestions:login") else: return render(request, self.template_name, {"form": form}) # models.py class CustomUser(AbstractUser): phone_number = models.CharField(max_length=20) REQUIRED_FIELDS = ["first_name", "last_name", "phone_number"] # forms.py class RegistrationForm(forms.ModelForm): confirm_password = forms.CharField(label="Confirm password:", max_length=200, widget=forms.PasswordInput(attrs={"class": "form-control"})) class Meta: model = CustomUser fields = ["first_name", "last_name", "username", "phone_number", "password",] labels = { "first_name": "Name:", "last_name": "Last name:", "username": "Username", "phone_number": "Phone number:", "password": "Password", "confirm_password": "Confirm password:", } widgets = { … -
uwsgi error can't get attribute 'MyModel' on <module'__main__'(built-in), but Django python manage.py runserver is OK
I put my Django project in docker, When I use python manage.py runserver, everything is OK. But using 'uwsgi --ini uwsgi.ini' start my project, it will be AttributeError: can't get attribute 'MyModel' on <module'__main__'(built-in) when I sent post request. There is my project structure db.sqlite uwsgi.ini │ manage.py │ mysql_test.py │ plt_score.py │ request_test.py │ test.log │ ├─Ai_Web │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ _init_.py │ │ │ ├─testapp │ │ admin.py │ │ apps.py │ │ bert_finetuned.py │ │ models.py │ │ random_forest.py │ │ tests.py │ │ urls.py │ │ views.py │ │ _init_.py My uwsgi file is [uwsgi] http = 0.0.0.0:8000 processes = 2 threads = 4 chdir = root/project/API_simple wsgi-file = Ai_Web/wsgi.py master = true manage.py have import the model class 'MyModel', so runserver is OK;But uwsgi will be wrong -
how to avoid overlapping requests when creating new objects?
def artist(request): print("START") if request.method == "GET": try: if artist_id: artist = Artist.objects.get(pk=artist_id) else: artist = Artist.objects.get(user=request.user) print("artist exists") except Artist.DoesNotExist: print("artist doesn't exist") artist = Artist.objects.get_or_create(user=request.user)[0] print("a new artist object has been created") return HttpResponse(status=200) Console: START artist doesn't exist START artist doesn't exist a new artist object has been created [15/Dec/2022 12:40:23] "GET /artist/ HTTP/1.1" 200 0 a new artist object has been created [15/Dec/2022 12:40:23] "GET /artist/ HTTP/1.1" 200 0 on the client side, there is a button on the screen that sends a request that returns to the user their artist page, or if they don't have one, it will be created for them. And suppose he double clicks the button, then two objects will be created. The user field in the Artist is not unique, we ignore the fact that we can solve the problem on the client side with javascript and we assume that the server is a bit slow, so it doesn't have time to process two requests in such a short time. The Artist model has a field that at the time of creation must be populated with some information based on their profile picture, i.e. i extract the dominant color from … -
Input give in the form not saving to the database
This is the model i created make a form. Two more fields are added in the form by using abstract user. models.py from django.db import models from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): phone=models.CharField(max_length=20) profile_pic=models.ImageField(upload_to="dp",null=True,blank=True) Registration form is inherited from UserCreationForm. forms.py from django.contrib.auth.forms import UserCreationForm from socialapp.models import MyUser from django import forms class RegistrationForm(UserCreationForm): widgets={ "password1":forms.PasswordInput(attrs={"class":"form-control"}), "password2":forms.PasswordInput(attrs={"class":"form-control"}) } class Meta: model=MyUser fields=["first_name","last_name", "username","email", "phone","profile_pic", "password1","password2"] widgets={ "first_name":forms.TextInput(attrs={"class":"form-control"}), "last_name":forms.TextInput(attrs={"class":"form-control"}), "username":forms.TextInput(attrs={"class":"form-control"}), "email":forms.TextInput(attrs={"class":"form-control"}), "phone":forms.TextInput(attrs={"class":"form-control"}), "profile_pic":forms.FileInput(attrs={"class":"form-control"}), } Here is the view to map to the template views.py from django.shortcuts import render from socialapp.forms import RegistrationForm from socialapp.models import MyUser from django.views.generic import CreateView from django.urls import reverse_lazy class SignupView(CreateView): model=MyUser form_class=RegistrationForm template_name="register.html" success_url=reverse_lazy("register") -
How to raise an exception in a serializer when the request.user belong to a different model?
I use a custom User model in my application and created two other models inherited from it, called Manager and Client, each one with specific fields. With DRF I'm trying to create two endpoints /manager and /client so that both types of user can get their profile data. However, when a manager GET /client his own data are returned because the view ClientDetailsView returns self.request.user, and this Manager object can be serialized with ClientSerializer because the two models are inherited from User. My question is it possible to check the model's class in the serializer so that ClientSerializer raise an exception when a manager visit the endpoint ? or more globally, what is the best way to address the issue ? models.py class User(AbstractBaseUser, PermissionsMixin): ... class Manager(User): ... class Client(User): ... view.py @permission_classes([IsManager]) class ManagerDetailsView(RetrieveAPIView): queryset = Manager.objects.all() serializer_class = ManagerSerializer def get_object(self): return self.request.user @permission_classes([IsManager | IsClient]) class ClientDetailsView(RetrieveAPIView): queryset = Client.objects.all() serializer_class = ClientSerializer def get_object(self): return self.request.user serializer.py class ManagerSerializer(serializers.ModelSerializer): password1 = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) fields = serializers.JSONField(write_only=True) def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError('Passwords must match.') return data def create(self, validated_data): data = { key: value for key, value in validated_data.items() if … -
how to send django formset data with ajax?
first I want get data from form and then send this data to server with ajax... <script> document.querySelector('form').addEventListener('submit', (e) => { const data = Object.formEntries(new FormData(e.target).entries()); console.log(data); SubmitButtonClicked(); }); </script> <script> function SubmitButtonClicked(){ $.ajax({ dataType:"json", type:"POST", url:"{% url 'meraj_public:new_rrr' %}", data: { csrfmiddlewaretoken: "{{ csrf_token }}", data: data, }, success: function(response){ let success = response.success; if (succes === false){ alert('error'); }else{ alert('success') } } }) } </script> but here, data not diplay on console and there was an error: Uncaught ReferenceError SubmitButtonClicked is not defined -
AttributeError: 'QuerySet' object has no attribute 'url'
this code has this error and I am absolutely lost how to fix it. the code runs fine until it gets to the last object saved in the database and after that it throws this error. the code is a tool that checks the html of a website between 2 points in time to check if it has an error, even if the website is running well and giving a 200 response code This is the error: in check_html print(monitor.url) AttributeError: 'QuerySet' object has no attribute 'url' `def run_monitors(): delete_from_db() monitors = Monitor.objects.filter(is_active=True) monitors._fetch_all() asyncio.run(_run_monitors(monitors)) check_html(monitor=monitors)` `def check_html(monitor): start_time = time.time() print(monitor.url) # The URLs to compare old_html = monitor.html_compare new_url = monitor.url # Get the HTML of each URL try: old_html = old_html # html1.raise_for_status() except Exception as e: print(e) try: html2 = requests.get(new_url) html2.raise_for_status() except Exception as e: print(e) return None html2 = html2.text[:10000] # Create a SequenceMatcher object to compare the HTML of the two URLs matcher = difflib.SequenceMatcher(None, old_html, html2) similarity_ratio = matcher.ratio() * 100 response_time = time.time() - start_time monitor.html_compare = html2 html_failure = False counter = monitor.fault_counter if similarity_ratio <= 90 and counter == 0: print(f"The two HTMLs have {similarity_ratio:}% in common.") print("change detected") … -
Django FormModel fields not found
Currently, the template is only generating the Submit button without any input fields. Also, if I change fields = "all" to fields= ["email","name"] it tells me that these fields do not exist. class NewsletterSubscriber(models.Model): email = EmailField(required=True, label='Email') name = CharField(required=True, label='Name') class SubscribeForm(forms.ModelForm): class Meta: model = NewsletterSubscriber fields = "__all__" def subscribe(request): form = SubscribeForm() if request.method == 'POST': form = SubscribeForm(request.POST) if form.is_valid(): form.save() # redirect to a success page return render(request, 'subscribe.html', {'subscribeForm': form}) <form action="{% url 'subscribe' %}" method="post"> {% csrf_token %} {{ subscribeForm.as_p }} <input type="submit" value="Subscribe"> </form> -
Django Queryset filter datetimefield using time interval
I've got a field in one model like: class Sample(models.Model): created_at = models.DateTimeField(auto_now_add=True, blank=True) this is what it's looks like if saved: 2022-12-13 13:00:29.84166+08 2022-12-13 14:00:29.84166+08 2022-12-13 15:00:29.84166+08 Is it possible to filter that by range of time? maybe similar to this? Sample.objects.filter(created_at __range=["13:00", "15:00"]) I have tried this but it's not working Sample.objects.filter(created_at__time__range=["13:00", "15:00"]) I want to get all the data that ranged with "13:00", "15:00" in different dates -
How can I create a post with Django crispy forms?
I want to add a form so users can create a new post. So I added the following code: {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="boder-bottom mb-4">Inserat erstellen</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> {% endblock content %} But this is what it end up looking like. I followed the steps from a Youtube Tutorial and the result looks different than mine. What am I'm missing ? -
Mptt model does not return {{ children }}
I have Deviz model that inherits from MPTTmodel. I populated the database with data but can't get to show the children. The tree should be like : Chapter 1 -Subchapter 1 --SubSubchapter 1 ---Article 1 ---Article 2 ---Article 3 Chapter 2 -Subsubchapter1 --Article 1 --Article 2 In the template it only displays the Chapters. When change object_list to object_list.get_descendants, it does not display the first level tree (Chapters) models.py class Deviz(MPTTModel): lucrare = models.ForeignKey(Lucrare, on_delete=models.CASCADE,default='',null=True,related_name="deviz") parent = TreeForeignKey('self', on_delete=models.CASCADE,null=True,blank=True,related_name='children') cod = models.CharField(default='', max_length=20,verbose_name="Cod") norma = models.CharField(default='',max_length=20,verbose_name="Norma") denumire = models.TextField(default='',verbose_name="Denumire") um_articol = models.TextField(default='',verbose_name="Um") oferta = models.FloatField(default=0,verbose_name="Cant Oferta") buget = models.FloatField(default=0) cost = models.FloatField(default=0) def __str__(self): return self.denumire class Meta: verbose_name = 'Deviz' verbose_name_plural = 'Devize' views.py class DevizListview(LoginRequiredMixin, CoreListView): model = Deviz template.html {% recursetree object_list %} <li> {{ node.denumire }} {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} -
Display product images from a loop using django
I would like to display my images from a loop, my images are stored on static/images and in the database the image field is a CharField of image name. settings.py STATICFILES_DIRS = [ BASE_DIR / 'static', ] STATIC_URL = 'static/' LOGIN_REDIRECT_URL='account:profile' LOGIN_URL='account:login' models.py class Product(models.Model): name=models.CharField(max_length=70,blank=True,null=True) price=models.IntegerField() image=models.CharField(max_length=100,blank=True,null=True) views.py {% load static %} {% for product in products %} <div class="card"> <div class="card-image"> <img src="{% static 'images/{{product.image}}' %}"> </div> </div> {% endfor %} I can't display the image. How to do ?? -
Mock few lines of a function for Unit Tests
I have this below function for which I would like to write unit tests. def fetch_latest_topics(request): username = request.META['username'] try: client = create_discourse_connection(username) response = client.latest_topics() topic_list = response['topic_list']['topics'] filtered_topics_data = [] for topic in topic_list: filtered_topics_data.append( { "title": topic["title"], "created_at": topic["created_at"], "topic_id": topic["id"] } ) except Exception as e: return sendResponse(formatErrorResponse(badreq_err, str(e))) return sendResponse({"post_replies": filtered_topics_data}) I want to mock below lines client = create_discourse_connection(username) response = client.latest_topics() Basically In these lines, I will create a connection with external server and fetch some response. I don't want to do this in unit test (Since this is a library it will be tested beforehand and it's not my code responsibility to test this). I just have to pass a mock response json and validate the response formatting and keys in my unit test. I explored mock library for mocking functions but this is more of a library and it's method call rather than a plain function. It will be a great help if someone can show me the direction to test this. Thank you for giving time to this question. -
Replacing Nginx with Traefik caused Django to use admin files via HTTP instead of HTTPS, breaking functionality
I had a perfectly fine Django CMS 3.4.1 setup running behind Nginx as an edge-server with SSL termination. The complete chain was: nginx (SSL) → nginx (django server) → gunicorn → django All I did was to replace the first nginx reverse proxy with traefik, for a better integration of other services. Everything is run with docker (compose) The issue is, that Django now wants to redirect HTTPS calls to admin files (and ajax calls) to HTTP, breaking functionality because those files are blocked by the browser. I did not change anything with the django installation. In fact, it even is the same docker image as before. Because it did work with the old setup, I don't think that it is an issue with the Django CMS code using hardcoded http://. SSL was terminated before the django reverse proxy, as well. Does anyone see something I am missing? Here are some configuration files, from top to bottom: traefic.yml: global: sendAnonymousUsage: false api: dashboard: true insecure: true providers: docker: endpoint: "unix:///var/run/docker.sock" watch: true exposedByDefault: false log: level: INFO format: common entryPoints: http: address: ":80" http: redirections: entryPoint: to: https scheme: https https: address: ":443" certificatesResolvers: letsencrypt: acme: email: *** storage: /etc/acme/acme.json … -
javascript querySelectorAll is not working on all django objects in the template
I'm working on Auctions website using Javascript and Django. I want to make each user has the ability to view products that he has participated in whether by selling , competition by bids or won bids. So I created a page containing three buttons(won, selling , competiting). On clicking on each buttons , shows the related products(change the display on click). Until now it works. The problem that I want in each product card on mouse over it shows certain div and on mouse out it shows another div. I created the functionality using Javascript (by forEach card in query that selects all cards). the problem that this functionality works on certain cards but upon clicking on the buttons that shows won or competition products, it doesn't work on the related cards (not working on all cards). html: <div class="container"> <div id="userbidsbuttons"> <button class='userbidsbu'id="viewsell">Posted</button> <button class='userbidsbu'id="viewbuy">Won</button> <button class='userbidsbu'id="viewnow">In competition</button> </div> <div class="indexobj"> <div id="viewselluser"> {% if yy.0 is not None%} {% for obj in yy %} <div class="card {{obj.bidcategory}}" style="width: 18rem;" id="{{obj.id}}"> <img class="card-img-top" src="..{{obj.image.url}}" alt="Card image cap"> <div class="thecardcontent" id="co{{obj.id}}"> <div class="card-body"> <h5 class="card-title">{{obj.name}}</h5> <p class="card-text">{{obj.bidcategory.category}}</p> </div> <ul class="list-group list-group-flush"> <ul class="list-group-item"><li ><i class="fa-solid fa-car"></i> {{obj.model}}</li> <li ><i class="fa-solid … -
ChoiceField blank if none of the choices is selected
I'm making a ChoiceField dropdown, but i want to make sure it's empty until unless any of the given choices is selected input_type_mapping = forms.ChoiceField(choices=INPUT_CHOICES,required=False) currently it looks like this: i tried adding blank = true input_type_mapping = forms.ChoiceField(choices=INPUT_CHOICES,required=False, blank = True) but getting the error TypeError: init() got an unexpected keyword argument 'blank' Help me out with this -
Django url call in ajax success innerhtml
I have the below code, $.ajax({ url: '{% url "load" %}', type: 'GET', data: { }, success: function (response) { const data = response.fs content_container.innerHTML = "" data.map(full => { content_container.innerHTML += `<a href="{%url 'business_sale_cust' id=${full.id} btype=${full.interested %}}"> <div class="border border-success mt-2 pl-2"> <h3>${full.companyName}</h3> <p>${full.inputEmail}</p> </div></a>` }) but getting error with <a href="{%url 'business_sale_cust' id=${full.id} btype=${full.interested %}}. please let me know how to pass the parameter id and interested with url. Let me know how to pass the django url within ajax innerhtml. -
How to trigger an email on field change
I have a contact form that users can use to send complaints. However, I want a situation where the support team can indicate if a complaint is resolved or not and it will trigger an email when the status change to 'Resolved'. By default, the complaint is 'pending'. I am currently using a signal. Please, can someone help me because it's not sending email when the status change to 'Resolves'. what am I not doing right? This is what I did: @receiver(pre_save, sender=Contact) def send_email_on_status_change(sender, instance, **kwargs): # Check if the field that you want to watch has changed if instance.status == 'Resolved': # Construct and send the email subject = "Contact status changed" message = "the status of this complaint has changed to has changed to '{}'".format(instance) send_mail( subject, message, 'sender@example.com', ['recipient@example.com'], fail_silently=False, ) @receiver(pre_save, sender=Contact) def save_status(sender, instance, **kwargs): instance.status.save()@receiver(pre_save, sender=Contact) def send_email_on_status_change(sender, instance, **kwargs): # Check if the field that you want to watch has changed if instance.status == 'Resolved': # Construct and send the email subject = "Contact status changed" message = "the status of this complaint has changed to has changed to '{}'".format(instance) send_mail( subject, message, 'sender@example.com', ['recipient@example.com'], fail_silently=False, ) -
Can I create 2 dictionary from only one loop over queryset
This is my code right now : booking_data = {p: 0 for p in vehicle_category.types.all()} vehicle_type_mapping = {k.id: k for k in vehicle_category.types.all()} I wonder if there is a way i can create those 2 dict only with one loop. Or is there another way more efficiently that i can do.