Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to connect and access user and groups from Windows AD from Django web application
How to connect and access user and groups from Windows AD from Django web application ? I need to create a DJANGO web application to establish connection with Windows AD and access user and groups Access users Add user to group Remove user from group List groups -
Issue with duplication of model instanc using save()
I have following models: class Employee(models.Model): # some fields class EmployeeHistory(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) # some fields I want to record new EmployeeHistory as soon as Employee instance was created. employee = Employee( # some fields are filled ) employee.save() history=EmployeeHistory( employee=employee, # some fields are filled ) history.save() In this case I have two same recently added Employee records. I've tried to remove employee.save() but have save() prohibited to prevent data loss due to unsaved related object 'employee'. How could I save both of these instances without duplication of Employee? -
Django: Combining two queries into one
I currently struggle to combine query_1 and query_2 into one query_combined. Do you have an idea how to achieve that? query_1 = ( Response.objects.filter( survey__event=12, survey__template=settings.SURVEY_POST_EVENT, answers__question__focus=QuestionFocus.FEELING_ABOUT_ATTENDING_AGAIN, ).filter(answers__answer="Very disappointed") ) query_2 = ( Response.objects.filter( survey__event=12, survey__template=settings.SURVEY_POST_EVENT, answers__question__focus=QuestionFocus.RECOMMENDATION_TO_FRIENDS, ) .annotate(answer_num=Cast("answers__answer", IntegerField())) .filter(answer_num__gt=8) ) -
Geodjango Import Shapefile with LayerMapping and OGR
I am trying to load a shapefile into Django When I'm running this: simon@DESKTOP-V82N14G:/mnt/c/WINDOWS/system32/poc_dashboard/pocdash$ ogrinfo -ro -so testdjango/data/vnm_polbn_adm3_2014_pdc.shp INFO: Open of `testdjango/data/vnm_polbn_adm3_2014_pdc.shp' using driver `ESRI Shapefile' successful. 1: vnm_polbn_adm3_2014_pdc (Polygon) When I use python shell to run my code: python manage.py shell from testdjango import load_layer load_layer.run() It returns me : Traceback (most recent call last): File "<console>", line 1, in <module> File "/mnt/c/WINDOWS/system32/poc_dashboard/pocdash/testdjango/load_layer.py", line 27, in run lm = LayerMapping(Adm3_names, adm3_name_shp, adm3_name_mapping, transform= False, encoding='iso-8859-1') File "/mnt/c/WINDOWS/system32/poc_dashboard/poc/lib/python3.6/site-packages/django/contrib/gis/utils/layermapping.py", line 92, in __init__ self.ds = DataSource(data, encoding=encoding) File "/mnt/c/WINDOWS/system32/poc_dashboard/poc/lib/python3.6/site-packages/django/contrib/gis/gdal/datasource.py", line 74, in __init__ raise GDALException('Could not open the datasource at "%s"' % ds_input) django.contrib.gis.gdal.error.GDALException: Could not open the datasource at "/mnt/c/WINDOWS/system32/poc_dashboard/pocdash/testdjango/testdjango/data/vnm_polbn_adm3_2014_pdc.shp" Is it something wrong with my code or something wrong with my shapefile? I attached the file here import os from django.contrib.gis.utils import LayerMapping from django.contrib.gis.db import models from .models import Adm3_names adm3_name_mapping = { 'gid': 'gid', 'adm1_code': 'adm1_code', 'adm1_name': 'adm1_name', 'adm2_code': 'adm2_code', 'adm2_name': 'adm2_name', 'adm3_code': 'adm3_code', 'adm3_name': 'adm3_name', 'adm3_statu': 'adm3_statu', 'pop': 'pop', 'pop_0to14': 'pop_0to14', 'pop_65plus': 'pop_65plus', 'hh': 'hh', 'shape_leng': 'shape_leng', 'shape_area': 'shape_area', 'geom': 'MULTIPOLYGON', } adm3_name_shp = os.path. abspath(os.path.join(os.path.dirname(__file__),'testdjango/data/vnm_polbn_adm3_2014_pdc.shp')) def run(verbose=True): lm = LayerMapping(Adm3_names, adm3_name_shp, adm3_name_mapping, transform= False, encoding='iso-8859-1') lm.save(strict=True,verbose=verbose) -
Django tests parallel issues
Django ver: 1.11.25, PostgreSQL ver: 11.5 So I'm having some issues trying to run my django tests in parallel. I've tried setting the (--parallel) flag, which is able to create copies of the test db, however it runs all of them under the main thread and doesn't create any other threads. My tests need to call the class's setUpClass to populate the databases up to a certain point, dumpdata into a fixture, and then each setUp they loaddata off that fixture (which is working correctly). The only problem I'm faced with is that it's all run sequentially instead of in parallel. I tried using django-nose (--processes) flag, but this simply runs my setUpClass per process, and it only creates the one test db for all the processes to share. My test class is a StaticLiveServerTestCase. Any info is appreciated! -
low weight packages in python to run async task
Apart from celery and asyncio are there any other low weight packages in python to run async task. I don't want to run another server as the number of background task are low. -
Comparing two rows from the same table
I have two rows from the same table and I want to get the column names with different values for these rows. I know I can get this with a simple for loop but perhaps django already has a method to get this done. -
Boolean Field always saving False django
I am using Django Rest Framework, when the payload comes from post request i have a boolean field of company_status, this field is true but when the user saves it becomes False, I can't get what the problem is: class CreateUser(APIView): def get(self,request): return Response([UserSerializer(dat).data for dat in User.objects.all()]) def post(self,request): payload=request.data serializer = UserSerializer(data=payload) print(payload) # here it shows company_status True if serializer.is_valid(): instance = serializer.save() instance.set_password(instance.password) instance.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id','username','user_image','designation','company_status','age','gender'] def create(self, validated_data): user = User.objects.create(**validated_data) return user def update(self, instance, validated_data): for k, v in validated_data.items(): setattr(instance, k, v) instance.save() return instance class User(AbstractBaseUser,PermissionsMixin): # is_admin=models.BooleanField(default=False) is_staff = models.BooleanField(default=False) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) date_joined = models.DateTimeField(null=True, blank=True) user_image=models.ImageField(upload_to=user_main_image_directory_path,null=True,blank=True) username = models.CharField( max_length=150, unique=True, null=True, ) is_active = models.BooleanField(default=True) phonenumber=models.CharField(max_length=13,default="null") faceid=HashidField is_booker=models.BooleanField(default=False) designation=models.CharField(max_length=30,null=True) company_status=models.BooleanField(null=True,blank=True) # this is the field object = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] age=models.IntegerField(null=True) gender=models.CharField(max_length=10,null=True,blank=True) Response: "id": 1, "username": "nabeel", "user_image": "/media/1/opencv_frame_0.jpg", "designation": "bscs", "company_status": false, "age": 23, "gender": "male" } Can't get why it always save False in company_status, I have printed the payload comes from post request and it show True,but when serializer saves … -
Send request body to serializers
in my Django project, I have the following for serializers and views serializers: class AnimalSerializer(serializers.ModelSerializer): class Meta: model = Animal fields = [ 'pk', 'name', 'animal_type', 'weight', 'color', ] views: class AnimalRudView(generics.RetrieveUpdateDestroyAPIView): serializer = AnimalSerializer def create(self,request): body = json.loads(request.body.decode('utf-8') with connection.cursor() as cursor: cursor.execute("SELECT * FROM animals WHERE " + body['search']) animal = [dict(zip([column[0] for column in cursor.description], row)) for row in cursor.fetchall()] return Response(serializer.data) In views, I get a request body with certain conditions ( as " search ": " weight>20 "), which gives me then all objects which match these conditions. I want to add this body to the serializer as well because I want to fill the fields list automatically. Do you have any idea how I can parse the body into the serializer? Best regards -
Django urlpatterns define a url only receive int but without parameters' name
urlpatterns = [ path('products/<int:num>/', views.productview) ] with non-named integer parameter to the view. (an example URL "/products/523/") -
InvalidOperation at /orders/ [<class 'decimal.ConversionSyntax'>]
I am going to add delivery cost to total price in project but it does not work. Both fields are Decimal but it throws this error InvalidOperation at /orders/ [<class 'decimal.ConversionSyntax'>]. Here is Delivery price model class DeliveryPrice(models.Model): shipping_name = models.CharField(max_length=255, blank=True, null=True) shipping_charge = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) and it is the FK to Order model. serializers.py class OrderSerializer(serializers.ModelSerializer): price_of_delivery = serializers.DecimalField(max_digits=10, decimal_places=2) class Meta: model = Order fields = '__all__' def create(self, validated_data): price_of_delivery = validated_data.pop('price_of_delivery') price_instance, created = DeliveryPrice.objects.get_or_create(shipping_charge=price_of_delivery) order_instance = Order.objects.create(**validated_data, price_of_delivery=price_instance) return order_instance views.py total_aggregated_dict = cart.aggregate( total_price=Sum(F('quantity') * F('product__price'), output_field=DecimalField())) print(total_aggregated_dict) order_total = total_aggregated_dict['total_price'] delivery_price = self.request.data['price_of_delivery'] print(delivery_price) final_total = Decimal(order_total) + Decimal(delivery_price) print(final_total) order = serializer.save(user=user, total_price=final_total) this is all what I have tried so far. To be clear, firstly, user adds product to cart then they can order when they fill order fields (address, phone number, etc) they also select shipping cost and this selected shipping cost should be added to total price. But in my case it is not working I am getting error above shown. How can i tackle this issue? Any help please? Thanks in advance! -
Is it possible to use ZeroMQ sockets in a Django Channels Consumer?
I've got a hobby project of building an autonomous boat. I now built a GUI using a Vuejs frontend and a Django backend. In this GUI I can see the boat on a map, and send commands to it. Those commands are sent over ZeroMQ sockets which works great. I'm using Django channels to send the commands from the frontend over a websocket to the backend and from there I send it on over the ZeroMQ socket. My consumer looks as follows: import zmq from channels.generic.websocket import WebsocketConsumer from .tools import get_vehicle_ip_address, get_vehicle_steer_socket context = zmq.Context() class SteerConsumer(WebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.forward_steer_socket = get_vehicle_steer_socket(context, get_vehicle_ip_address()) def connect(self): self.accept() def receive(self, text_data): print("Passing on the commands from the frontend:", text_data, "to the boat") self.forward_steer_socket.send_string(text_data) Next to this I also receive location information from the boat over a ZeroMQ socket which I save to the database. I'm running this in a separate script and the frontend simply polls the backend every 2 seconds for updates. Here's the script receiving the boat info: import os import django import zmq os.environ['DJANGO_SETTINGS_MODULE'] = 'server.settings' django.setup() # Socket to receive the boat location context = zmq.Context() location_socket = context.socket(zmq.SUB) location_socket.setsockopt(zmq.CONFLATE, True) location_socket.bind('tcp://*:6001') location_socket.setsockopt_string(zmq.SUBSCRIBE, … -
use clusterize.js library with django
Hi I'm trying to test using clusterize.js with my django app, the hope is to use it to load large tables with hundreds of rows of data on my html page. I am loading this html file in a view as an httpResponse: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link rel='icon' href="{% static 'images/icon.png' %}" type='image/x-icon' /> <link href="{% static 'clusterize/clusterize.css' %}"> <link href="{% static 'clusterize/clusterize.min.js' %}"> <!-- <link href="./clusterize.css" rel="stylesheet"> <script src="./clusterize.min.js"></script> --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content="popularify"> <meta name="author" content="martinbarker"> <title>popularify</title> </head> <body> <div>test</div> <button onclick="myFunction()">Call myFunction()</button> <div id="scrollArea" class="clusterize-scroll"> <div id="contentArea" class="clusterize-content"> <div class="clusterize-no-data">Loading data…</div> </div> </div> </body> <script> async function myFunction() { console.log("myFunction()") var data = ['<div>1…</div>', '<div>2…</div>', '<div>3</div>']; var clusterize = new Clusterize({ rows: data, scrollId: 'scrollArea',contentId: 'contentArea' }); } </script> My static files load fine, and there are no initial errors in console when I load the page, but when I click the button, which calls the js function, i get the error: Uncaught (in promise) ReferenceError: Clusterize is not defined Pointing to the line: var clusterize = new Clusterize({ rows: data, scrollId: 'scrollArea',contentId: 'contentArea' }); If I am trying to load clusterize.js using … -
Regarding flipkart marketplace seller api
I am trying to fetch the flipkart orders using marketplace seller api. I am using https://seller.flipkart.com/api-docs/order-api-docs/SearchOrderRef.html url. But i am getting only the cancelled orders, not all orders. Please tell me how to fetch all orders. This is my function. Thank you. def get_filter_orders(self): api_address = f'{flipkart_api_url}/v2/orders/search' filter_orders = Filter.objects.all() for filter_order in filter_orders: pass payload = {"filter": {"states": ["APPROVED", "PACKED", "READY_TO_DISPATCH", "CANCELLED"], "orderDate": {"fromDate": filter_order.order_date_from, "toDate": filter_order.order_date_to}, "dispatchAfterDate": {"fromDate": filter_order.dispatch_after_date_from, "toDate": filter_order.dispatch_after_date_to}, "dispatchByDate": {"fromDate": filter_order.dispatch_by_date_from, "toDate": filter_order.dispatch_by_date_to}, "modifiedDate": {"fromDate": filter_order.modified_date_from, "toDate": filter_order.modified_date_to}}, "pagination": {"pageSize": filter_order.page_size}, "sort": {"field": filter_order.sort_field, "order": filter_order.sort_order}} headers = { "Authorization": f"Bearer {access_token}", "content-type": "application/json", } response = requests.post(api_address, data=json.dumps(payload, cls=DjangoJSONEncoder), headers=headers) dict_response = response.json() orderData = dict_response.get('orderItems', '') for orderItem in orderData: orders_data = {} if orderItem.get('orderId'): orders_data['order_id'] = orderItem.get('orderId') orders_data['order_item'] = orderItem.get('orderItemId') orders_data['title'] = orderItem.get('title') orders_data['sku'] = orderItem.get('sku') orders_data['order_date'] = orderItem.get('orderDate') only_date = orders_data['order_date'].split('T')[0] # print(only_date) orders_data['deliver_by_date'] = orderItem.get('deliverByDate') orders_data['status'] = orderItem.get('status', '') orders_data['total_price'] = orderItem['priceComponents']['totalPrice'] # print(orders_data['total_price']) # import pdb;pdb.set_trace() try: Orders.objects.update_or_create(order_id=orders_data['order_id'], order_item=orders_data['order_item'], title=orders_data['title'], sku=orders_data['sku'], order_date=only_date, deliver_by_date=orders_data['deliver_by_date'], status=orders_data['status'], total_price=orders_data['total_price']) print('created', Orders.objects.count()) except Exception as e: print("Order ID already exists", e) return dict_response -
How to customized Django filter by adding a custom choice?
# models.py class pro(models.Model): STATUS_CHOICES = ( ('hi', 'hi'), ('bye', 'bye'), ('yo', 'yo'), ) status = models.CharField(max_length=20, choices=STATUS_CHOICES) # views.py import django_filters class customfilter(django_filters.FilterSet): # insert some code here class Meta: model = pro fields = ['status',] class proview(FilterView): template_name="1.html" filterset_class = customfilter # 1.html <form action="" method="get"> {{ filter.form.as_p }} <input type="submit" /> </form> how to let the dropdown in template render the choice like this? Thank you very much ('hi') ('bye') ('yo') ('hi or bye") -
Slack Integration in Python
I am trying to integrate slack in my python-django code and I was going through the documentation this one. I am not able to understand what is the path/to/my_message.slack refer to. from django_slack import slack_message slack_message('path/to/my_message.slack', { 'foo': Foo.objects.get(pk=17), }) Where path/to/my_message.slack (in your templates directory) : {% extends django_slack %} {% block text %} Message text here: {{ foo.bar|urlize }} {{ foo.user.get_full_name|safe }} {% endblock %} Help! -
Getting slider data in template
I need slider in my website and I have tried these things as mentioned below but I cannot get the data from the database in template. Is the process of getting data from database is wrong. How to get the data in template I am really confused how to do these things. Model.py class AddImage(models.Model): name=models.CharField(max_length=100,blank=False) image=models.ImageField(upload_to='img') publish=models.BooleanField(default=True) def __str__(self): return self.name views.py def index(request): slider_img=AddImage.objects.all() context = { 'slider_img':slider_img } return render(request,'home.html',context) home.html <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> {% for img in slider_img %} {% if img.publish %} <div class="carousel-item active"> <img class="d-block w-100" src="{{ img.image.url }" alt="First slide"> </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> {% endif %} {% endfor %} </div> </div> -
regular expression
regex that if we give "somebody" it should match with "some" array{some,build,other,} ex: input "BodyBuilder", it should match with "build" input "otherThan", it should match with "other" -
django checkbox yes or no
<form id="form" name="form"> <input type="checkbox" value="1" name="C" data-form-field="Option" class="form-check-input display-7" id="checkbox1"> <input type="checkbox" value="1" name="python" data-form-field="Option" class="form-check-input display-7" id="checkbox1"> <input type="checkbox" value="1" name="Csharp" data-form-field="Option" class="form-check-input display-7" id="checkbox1" > </form> <script> $(document).ready(function() { $("#submit").on('click', function() { console.clear() $('input[type=checkbox]').each(function () { if ($(this).prop('checked')==true) console.log($(this).prop('checked')); else console.log($(this).prop('checked')); }); }) }) </script> how to save into the database if the user checked it must be yes in the database, or if the checkbox is unchecked it must be no in the database? my problem is everytime I unchecked those three and save it into my database the result in database always automatic checked, i dont know if i am doing right in my javascript this is my views.py Clang = request.POST["C"] python = request.POST["python"] Csharp = request.POST["Csharp"] V_insert_data = known_Language( Clang =Clang , python =python , Csharp =Csharp ) V_insert_data.save() this is my models.py class known_Language(models.Model): Clang = =models.BooleanField(null=True, blank=True) python = =models.BooleanField(null=True, blank=True) Csharp==models.BooleanField(null=True, blank=True) -
Django ElasticSearch returns only 10 rowsets
I am using ElasticSearch-DSL in my django application and the query returns only 10 rows. When I use size. I get an error "multi_match" query does not support size. from django.shortcuts import render from elasticsearch_dsl import Q from elasticsearch_dsl.query import MultiMatch # Create your views here. from search.documents import CarDocument from products.models import Products def search(request): q = request.GET.get('q') if q: #cars = CarDocument.search().query("match", model_name=q) q = request.GET.get('q', None) query1 = MultiMatch(query=q, fields=['product_make', 'bodystyle','model_name','variant','transmission','yom']) s = CarDocument.search().query(query1) cars = s.execute() else: cars = '' return render(request, 'search/search.html', {'cars': cars}) -
Custom User Model in Django 2.2
I want to make a admin dashboard and here lots of user profiles with extra fields so I need a reference URL using function and Class View functions. -
GeoDjango Gdal exception cant open data source
I have this shapefile which I want to import with Django. My folder with the shapefile contains: vnm_polbn_adm3_2014_pdc.dbf vnm_polbn_adm3_2014_pdc.prj vnm_polbn_adm3_2014_pdc.qpj vnm_polbn_adm3_2014_pdc.shp vnm_polbn_adm3_2014_pdc.shx I use this code to create a model in Django which runs fine. python manage.py ogrinspect testdjango/data/vnm_polbnda_adm3_2014_pdc.shp Adm3_names --srid=4326 --mapping --multi When I run my load_layer file: import os from django.contrib.gis.utils import LayerMapping from .models import Adm3_names adm3_names_mapping = { 'gid': 'gid', 'adm1_code': 'adm1_code', 'adm1_name': 'adm1_name', 'adm2_code': 'adm2_code', 'adm2_name': 'adm2_name', 'adm3_code': 'adm3_code', 'adm3_name': 'adm3_name', 'adm3_statu': 'adm3_statu', 'pop': 'pop', 'pop_0to14': 'pop_0to14', 'pop_65plus': 'pop_65plus', 'hh': 'hh', 'shape_leng': 'shape_leng', 'shape_area': 'shape_area', 'geom': 'MULTIPOLYGON', } adm3_name_shp = os.path. abspath(os.path.join(os.path.dirname(__file__),'testdjango/data/vnm_polbnda_adm3_2014_pdc.shp')) def run(verbose=True): lm = LayerMapping(Adm3_names, adm3_name_shp, adm3_names_mapping, transform= False, encoding='iso-8859-1') lm.save(strict=True,verbose=verbose) It returns me : File "/mnt/c/WINDOWS/system32/poc_dashboard/poc/lib/python3.6/site-packages/django/contrib/gis/gdal/datasource.py", line 74, in __init__ raise GDALException('Could not open the datasource at "%s"' % ds_input) django.contrib.gis.gdal.error.GDALException: Could not open the datasource at "/mnt/c/WINDOWS/system32/poc_dashboard/pocdash/testdjango/testdjango/data/vnm_polbnda_adm3_2014_pdc.shp" I have checked that I have all the files extensions and that all the geometries are fine in QGIS. It seems there are no errors on the geometry. How can fix this error -
django login get AuthenticationForm doesnt contain get
I am trying to build a simple login form , but I am always getting 'AuthenticationForm' object has no attribute 'get'. I am new using django framework , but I am not sure how can it be fix thing issue ... any tips without changing too much logic ? view.py from django.shortcuts import render, redirect from django.views.generic import TemplateView from django.contrib.auth import authenticate from django.contrib.auth.forms import AuthenticationForm from django.http import HttpResponse class loginPage(TemplateView): template_name = 'login.html' def post(self, request): form = AuthenticationForm(request, data=request.POST) if form.is_valid(): user = authenticate( request, username=form.get('email'), password=form.get('password') ) if user is not None: return HttpResponse("Testing") else: print(user) else: return HttpResponse("loginPage") ## always goes here login html <form method="post"> {% csrf_token %} <input class="form-control" name="email" placeholder="Email" /></div> <input class="form-control" type="password" name="password" placeholder="Password" /> </form>``` -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xdd in position 0
Please help, when i run server compilator get me mistake - UnicodeDecodeError: 'utf-8' codec can't decode byte 0xdd in position 0: invalid continuation byte I'm using python 3.7 -
Django - How to add multiple fields from another table with a foreign key to list_display?
Let's say I have these two models: class Post(models.Model): pub_date = models.DateTimeField(auto_now=True) num_views = models.IntegerField(default=0) and class PostDetails(models.Model): title = models.CharField(max_length=128) text = models.TextField(max_length=512) language = models.CharField(max_length=2, default="en") # could be "en", "jp", "fr", etc... post = models.ForeignKey(Post, related_name="post", on_delete=models.CASCADE) user = models.ForeignKey(User, related_name="user", on_delete=models.CASCADE) class Meta: unique_together = ["post", "language"] I want to display the info from the PostDetails in the Post's list_display. In the admin.py file I have the following: class PostAdmin(admin.ModelAdmin): fieldsets = [...] inlines = [...] list_display = ["user", "en_title", "fr_title", "jp_title", "pup_date", "num_views"] # each one needs to be in its own column def en_title(self, obj): return obj.post.get(post=obj.id, language="en") def fr_title(self, obj): return obj.post.get(post=obj.id, language="fr") def jp_title(self, obj): return obj.post.get(post=obj.id, language="fr") Although this gives me the list_display I want, it adds a query for each column that I add from the PostDetails model. I thought about using prefetch_related and select_related, but I couldn't find a way to share the query set between functions. Is there anyway I could fetch all the data I need from the post_details table with a single query? Or at least as minimum queries as possible. What's the best way to achieve this?