Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to find Locations inside some range to a particular lat long. python
I am doing a project in flutter and i need to display only the events that are happening in the nearest locations. suppose my location is of latitude 11.2588 and longitude 75.7804. then i need to find events inside latitude 11.2588 +/- 2 and longitude 75.7804 +/-2. I need the backend python service for this. service for finding events occurring inside 2 days is as follows: I want code for finding events in the nearest locations merged inside this. class uview(APIView): def get(self, request): now = dt.now() + timedelta(days=2) d = now.strftime("%Y-%m-%d") ob = Events.objects.filter(date__lte=d) ser = android_serialiser(ob, many=True) return Response(ser.data) def post(self, request): now = dt.now() + timedelta(days=2) d = now.strftime("%Y-%m-%d") ob = Events.objects.filter(e_id=request.data['eid'],user_id=request.data['uid'],date__lte=d) ser = android_serialiser(ob, many=True) return Response(ser.data) any help would be greatly appreciated. Thanks in advance :) -
Django CBV filter corresponding data
I have this view class Dashboard (LoginRequiredMixin, ListView): model = SchulverzeichnisTabelle template_name = 'SCHUK/Dashboard.html' context_object_name = 'Dashboard' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['User'] = User.objects.all() context['Schulverzeichnis'] = SchulverzeichnisTabelle.objects.all() context['BedarfsBerechnung'] = Bedarfs_und_BesetzungsberechnungTabelle.objects.all() context['JahrgangGebunden'] = JahrgangsgebundenTabelle.objects.all() context['JahrgangUebergreifend'] = JahrgangsuebergreifendTabelle.objects.all() context['FoerderBedarf'] = FoerderbedarfschuelerTabelle.objects.all() context['VorbereitungsKlassen'] = VorbereitungsklassenTabelle.objects.all() context['EinzelIntergration'] = EinzelintegrationTabelle.objects.all() context['SonderPaedagogen'] = SonderpaedagogenbedarfTabelle.objects.all() context['Lehrer'] = LehrerTabelle.objects.all() context['GL_Lehrer'] = GL_LehrerTabelle.objects.all() return context I have 2 groups one for Admins and the other for User. And I want as an Admin see all data that a user has made in the template, and also make it editable. The goal is to have User views where User is allowed to edit his data While the Admins can look it up on the Dashboard and also edit it or create something for the User User data reders fine and everything is good Admin does it too if I use objects.all but in that case it shows everything after eacher other like school 1 school 2 school 3 class 1 class 2 class 3 teacher 1 teacher 2 teacher 3 and I want to bundle it like school 1 class 1 teacher 1 and so on -
hi..i'm trying to create website but it gives me this error
from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from . import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('Eshop.urls')) ]+static(settings.MEDIA.URL, document_root=settings.MEDIA_ROOT) this code gives me this ]+static(settings.MEDIA.URL, document_root=settings.MEDIA_ROOT) AttributeError: 'str' object has no attribute 'URL's error: how can i solve it -
How to send socket data from Django website?
I have a simple website with a button on it and I would like to connect that button to a websocket and send arbitrary data to the socket once it is pressed. I need to calculate the time it takes for the signal to be sent and received once the button is pressed. html file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Increment</title> </head> <body> {% block content %} Increment Counter <form id="form" method="post" action="#"> {% csrf_token %} <button type="submit", name="increment", value="increment">Increment</button> </form> <script type="text/javascript"> let url = `ws://${window.location.host}/ws/socket-server/` const chatSocket = new WebSocket(url) chatSocket.onmessage = function(e){ let data = JSON.parse(e.data) console.log('Data:', data) } </script> {% endblock %} </body> </html> I am very inexperienced so I am unsure how to do this. Any help would be appreciated. -
adding a user to a group on djngo admin and accessing it via views
if I add a user to a group on Django admin and assign permissions to the group, can I reference that user and its permissions in the views of my project? if yes how do I do it? thanks -
How do I use React with Django?
I have a Django project that currently run with a html template and vanilla js. If I want to shift the frontend to ReactJs. Is it possible to do so with minimal code changes in the backend? How big a change to the backend should I expect? -
no account logout Django Two factor auth
i am trying to implement two factor auth in my Django app. However, the user can bypass it by using the login provided by django.contrib.auth. is there any way i can redirect the user to /account/login when they browse for /login? Things i tried and have not work: removing django.contrib.auth (need this to logout) redundant login urls -
Django, model non-non-persistence field is None
In my model, I have a non-persistence field called 'client_secret'. The client_hash field is used in the custom model save method to calculate the hash. It worked as expected, but when I tried to save a new instance, self.client_secret is still None, why? class Client(models.Model): client_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) active = models.BooleanField(default=False) client_hash = models.BinaryField(editable=False, blank=True, null=True) # non-persistent field used to cal the hash client_secret = None def save(self, *args, **kwargs): if self._state.adding: self.client_hash = make_hash(self.client_secret) Trying to save a new client, client_secret is None in model save: Client.objects.create(active=True, client_secret='test_secret') -
how to fetch image from backend
import React from 'react' import { NavLink } from 'react-router-dom'; import * as ReactBootStrap from 'react-bootstrap' import "../Assets/styles/Supplier.css" import "../Assets/styles/button.css" import axios from "axios"; import { useEffect, useState } from 'react' const Supplier = () => { const [supplier, setSupplier] = useState([]) const [loading, setLoading] = useState(true) const [error, setError] = useState(false) // fetch data from the localhost and save it to the state useEffect(() => { setLoading(true) axios.get('http://127.0.0.1:8000/staff/supplier/') .then(res => { console.log(res.data) setSupplier(res.data) setLoading(false) }) .catch(err => { console.log(err) setError(true) }) }, []) return ( <> <body className="Body"> <section class="supplier_listing_whole"> <h1>Supplier listing</h1> <div class="supplier_listing"> <div className='button'> <NavLink to='/Supplier/SupplierForm' className={({ isActive }) => (isActive ? 'button-12' : 'button-12')}>registration</NavLink> </div> <ReactBootStrap.Table striped bordered hover> <thead> <tr> <th>id</th> <th>photo</th> <th>name</th> <th>email</th> <th>phone number</th> <th>birthdate</th> <th>identification card</th> </tr> </thead> <tbody> {supplier.map((supplier) => { return ( <tr key={supplier.id}> <td>{supplier.id}</td> <td> <img src={supplier.profile_picture} alt="image" class="picture" /> </td> <td>{supplier.user.first_name} {supplier.user.last_name}</td> <td>{supplier.user.email}</td> <td>{supplier.user.phone}</td> <td>{supplier.birthdate}</td> <td><img src={supplier.identification_card} alt={supplier.user.first_name} class="picture" /></td> </tr> ) })} </tbody> </ReactBootStrap.Table> </div> </section> </body> </> ) } export default Supplier; **i'm building a react js application and I'm finding a few thing a bit difficult since i'm relatively new to coding it self. For this instance i'm trying to fetch from Django API to … -
How to use order_by with last_added manytomanyfield?
Models.py class ChatRoomId(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_date = models.DateTimeField(auto_now_add=True) class MessageContent(models.Model): content = models.TextField(blank=True) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) class PersonalMessage(models.Model): message = models.ForeignKey(MessageContent, on_delete=models.CASCADE) sender = models.ForeignKey(CustomUser, on_delete=models.DO_NOTHING) class PersonalRoom(models.Model): room_id = models.ForeignKey(ChatRoomId, on_delete=models.CASCADE) user = models.ManyToManyField(CustomUser) message_list = models.ManyToManyField(PersonalMessage) modified_date = models.DateTimeField(auto_now=True) How to order this queryset PersonalRoom.objects.all() by the value "message__created_date" ManyToManyField last added message_list object, which is last_item = message_list.all().order_by('-message__created_date')[0]. My idea is PersonalRoom.objects.all().order_by( Subquery( PersonalRoom.objects.get(pk=OuterRef('pk')).message_list.all().order_by('-message__created_date')[0] ) ) but this results in an error. -
I get a KeyError in request.data[] on put method in postman while code works?
I have an api coded in django rest framework. there is an update method and no problem when the data is updated from the local host. but i get KeyError='Person' when i try to call put method on postman in the code below. @action(methods=['put'], detail=True, url_path='personupdate') def personupdate(self, request, pk): transactionSaveId = transaction.savepoint() # person = self.get_object(self,pk) person = Person.objects.get(id=pk) getPersonData = {} getPersonData = request.data['Person'] if 'PictureType' in request.data['Person']: request.data['Person'].pop('PictureType') if 'JobStartDate' in request.data['Person']: request.data['Person'].pop('JobStartDate') if 'FormerSeniority' in request.data['Person']: request.data['Person'].pop('FormerSeniority') serializer = PersonCreateUpdateSerializer(person, data=getPersonData) the data is updated in db when i called from the localhost api. In the ggetPersonData = request.data['Person'] line i get this error from postman: KeyError: 'Person' I've tried everything from postman but I can't fix it -
Error starting django web application in cpanel using application manager
enter image description here emphasized text I am facing an error while deploying my django application on server using application manager in cpanel. image is being attached to it. Please help me any answer is welcome. thanks -
get cart total is not called...get_product logic was working before and still works but now why is it showing an error?
models.py\account class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) is_paid = models.BooleanField(default=False) def __str__(self): return str(self.user) def get_cart_total(self): cart_item = self.cart_item.all() price = [] for cart_item in cart_items: price.append(cart_item.product.discounted_price) if cart_item.color_variant: color_variant_price = cart_item.color_variant.price price.append(color_variant_price) if cart_item.size_variant: size_variant_price = cart_item.size_variant.price price.append(size_variant_price) print(price) return sum(price) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) color_variant = models.ForeignKey(ColorVariant, on_delete=models.SET_NULL, null=True, blank=True) size_variant = models.ForeignKey(SizeVariant, on_delete=models.SET_NULL, null=True, blank=True) quantity = models.PositiveIntegerField(default=0) coupon = models.ForeignKey(Coupon, on_delete=models.SET_NULL, null=True, blank=True) def get_product_price(self): price = [self.product.discounted_price] if self.color_variant: color_variant_price = self.color_variant.price price.append(color_variant_price) if self.size_variant: size_variant_price = self.size_variant.price price.append(size_variant_price) return sum(price) views.py/shop def get_product(request,slug): try: product = Product.objects.get(slug=slug) context = {'product':product} if request.GET.get('size'): size = request.GET.get('size') price = product.get_product_price_by_size(size) context['selected_size'] = size context['updated_price'] = price print(price) return render(request, 'app/product-single.html',context = context ) except Exception as e: print(e) Product matching query does not exist. Internal Server Error: /favicon.ico/ Traceback (most recent call last): File "D:\online shopping\env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\online shopping\env\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response self.check_response(response, callback) File "D:\online shopping\env\lib\site-packages\django\core\handlers\base.py", line 332, in check_response raise ValueError( ValueError: The view shop.views.get_product didn't return an HttpResponse object. It returned None instead. [19/Aug/2022 11:45:30] "GET /favicon.ico/ HTTP/1.1" 500 63121 [19/Aug/2022 11:45:33] "GET /account/cart/ HTTP/1.1" 200 8204 Not Found: … -
Application error after deploy django app on heroku
I have successfully built and deployed my DJANGO app on the HEROKU. During building the application collectstatic also is running smoothly. But after everything completed successfully when I tries to open my app it is showing me application error. I have adding my recent log with this question. If anyone needs more information to analyze and give the solution then I can provide that also. recent log of heroku 2022-08-19T05:51:36.278162+00:00 app[api]: Initial release by user smit.dpatel9924@gmail.com 2022-08-19T05:51:36.278162+00:00 app[api]: Release v1 created by user smit.dpatel9924@gmail.com 2022-08-19T05:51:36.436285+00:00 app[api]: Enable Logplex by user smit.dpatel9924@gmail.com 2022-08-19T05:51:36.436285+00:00 app[api]: Release v2 created by user smit.dpatel9924@gmail.com 2022-08-19T05:51:57.696877+00:00 app[api]: Stack changed from heroku-20 to heroku-22 by user smit.dpatel9924@gmail.com 2022-08-19T05:51:57.713307+00:00 app[api]: Release v3 created by user smit.dpatel9924@gmail.com 2022-08-19T05:51:57.713307+00:00 app[api]: Upgrade stack to heroku-22 by user smit.dpatel9924@gmail.com 2022-08-19T05:52:24.000000+00:00 app[api]: Build started by user smit.dpatel9924@gmail.com 2022-08-19T05:53:26.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/4295d649-fdd6-4ff6-a915-07b881b4b295/activity/builds/614228a6-7a78-4922-ba2d-2bc5f297c905 2022-08-19T05:53:39.192112+00:00 app[api]: Release v4 created by user smit.dpatel9924@gmail.com 2022-08-19T05:53:39.192112+00:00 app[api]: Set DISABLE_COLLECTSTATIC config vars by user smit.dpatel9924@gmail.com 2022-08-19T05:53:45.000000+00:00 app[api]: Build started by user smit.dpatel9924@gmail.com 2022-08-19T05:55:33.534266+00:00 app[api]: Attach DATABASE (@ref:postgresql-symmetrical-16068) by user smit.dpatel9924@gmail.com 2022-08-19T05:55:33.534266+00:00 app[api]: Running release v5 commands by user smit.dpatel9924@gmail.com 2022-08-19T05:55:33.545559+00:00 app[api]: Release v6 created by user smit.dpatel9924@gmail.com 2022-08-19T05:55:33.545559+00:00 app[api]: @ref:postgresql-symmetrical-16068 completed provisioning, setting DATABASE_URL. … -
How to get domain in django template
I'm trying to build unsubscribe link in my email template but problem is i'm using seperate function in my utilites.py file to render my template and don't have access to request. This function is called by schedular in backend. I tried request.build_absolute_uri and other things but not able create the absulute link templates <body> <section class="tour section-wrapper container" id="notify-form"> <table id='datatable'></table> {{ content|safe }} {# <a href="{{ request.build_absolute_uri}}{% url 'delete' %}?email={{ sub_email }}">Unsubscribe</a>#} {# <a href="{% if request.is_secure %}https:/{% else %}http:/{% endif %}{{ request.get_host }}{{ request.build_absolute_uri }}{{ object.get_absolute_url }}{% url 'delete' %}?email={{ sub_email }}">Unsubscribe</a>#} <a href="{% if request.is_secure %}https://{% else %}http://{% endif %}{{ domain }}{% url 'delete' %}?email={{ sub_email }}">Unsubscribe</a> </section> <!-- /.tour </body> --> commented code is also what i tried tried using Sites framework but that gives doamin as example.com not what I expected utility method def send_notification(dataframe, email): subject = 'That’s your subject' from_email = 'xxxx@gmail.com' # 'from@example.com' text_content = 'That’s your plain text.' subscriber_email = QueryDetails.objects.get(email=email) domain = Site.objects.get_current().domain html_content = get_template('mail_template.html').render({'content': dataframe.to_html(classes=["table-bordered", "table-striped", "table-hover"]),'sub_email': subscriber_email, 'domain': domain}) Expected out put is if in local domain will be http://127.0.0.1/unsub/?email=xxxx@gmail.com if in production then http://whateverproductiondomain.com/unsub/?email=xxxx@gmail.com But if i run the program with one of commented code in … -
How to get all the users who have any relationship with a specific user in Django
I`m making a System where I need to get all the users who have a relationship with a specific user(the logged-in user). The relationship is like this I need all the users who have been joined by a user who also has been joined by another user until it reaches the logged-in user. My problem is to get the relationship to work so I can get all the users who have a relationship with the logged-in user I haven`t done any coding yet to show you guys... Please help me... Thank you, -
In Django Queryset, is there a way to update objects by group that are formed by group_by(annotations)?
My specific example : class AggregatedResult(models.Model) : amount = models.IntegerField() class RawResult(models.Model) : aggregate_result = models.ForeignKey(AggregatedResult, ...) type = models.CharField() date = models.DateField() amount = models.IntegerField() In this specific example RawResults have different type and date, and I'd like to make a queryset to aggregate them. so for example, I'd do something like : RawResults.objects.values("type","date").annotate(amount_sum = Sum("amount")) then I'd create AggregatedResult objects based off the results. Problem here is I have a ForeignKey relationship to AggregatedResult and I would like to assign proper foreignkey to RawResult, base off which objects have contributed to which result. for instance, assume : RawResult idx type date amount 1 A 10-04 10 2 A 10-04 8 3 A 10-05 7 4 B 10-04 5 running the queryset above will give me aggregated values, however, I want to update the RawResult objects to be properly mapped to AggregatedResult. So like : [ {A, 10-04, 18} new AggregatedResult(1) <- RawResult 1,2 should have aggregate_result = 1 {A, 10-05, 7} new AggregatedResult(2) <- RawResult 3 should have aggregate_result = 2 {B, 10-04, 5} new AggregatedResult(3) <- RawResult 4 should have aggregate_result = 3 ] I have moderate size of RawResult(500k ish), and little types (~15 types), and … -
How to solve Broken pipe from ('127.0.0.1', 63818) Error in Django
I can't upload most of the files even empty excel files in a small basic website built using Django, I am able to upload some files but in many cases I'm getting this error [19/Aug/2022 11:28:33,859] - Broken pipe from ('127.0.0.1', 63818) whenever I submit a form after uploading some file. I have searched for the solution many times online, I couldn't find one. Please help me with this... home_page.html : <form method="POST" enctype="multipart/form-data" > {% csrf_token %} <input type="file" name="file_selection1"> <input type="submit" name="upload"> </form> views.py : def home_page(request): if request.method == "POST": try: fs = FileSystemStorage(location='D:\outputs') fs.save(request.FILES['file_selection1'].name,request.FILES['file_selection1']) return render(request,"home_page.html",{'err':'upload successful'}) except: return render(request, "home_page.html", {'err': "can't upload"}) else: return render(request,"home_page.html",) -
How to use sockets to connect to Sqlite database in Django
I'm trying to write external scripts to my django project that will connect a socket to the sqlite database to listen to changes that happen to the tables. I will have threads supplying data to these tables and then I want to calculate the time taken for the system to detect changes in the database while monitoring it through sockets. I'm not sure if this is even possible, but I have been given this task. How can I achieve this? Do I need to use the standard channels module and setup consumers.py and routing.py for this or can I accomplish it in an external script? I have gone through websocket tutorials for django but I haven't been abole to figure out how I can connect to my database with what I learned. I am using Sqlite3 by the way. Any help is appreciated, thanks -
dajngo rest framework serializer.is_valid() not working [closed]
[enter image description here][1] please help [1]: https://i.stack.imgur.com/CWL8h.png -
Looking for suggestion, Django auth contrib groups, validate user if admin to a company
I'm looking for suggestions. What I have: User model Company model Groups (Admin, User) User can belong to many Company, but can only have one role on each company. Company 1 User 1 (admin), User 2(User) Company 2 User 1 (User), User 2(Admin) I would like to validate if User 1 is an ADMIN to Company 1, so I can give permission to user one on Company 1. As of now, I'm using django auth contrib group to give Role to user. Admin group (can create, update, delete) User group (can view only) What I have as of the moment is: request.user and request.user.groups.filter(name="Admin").exists() this is to validate if the user belongs to Admin. But I need to validate if the user is an ADMIN to Company. What I have in my head is: request.user and request.user.groups.filter(name="Admin").exists() and Company.objects.get(user__email='user1@example.com') #this validate if company has this user But this does not validate if User 1 is an Admin to Company 1. Looking for suggestions. I'm new to programming. Thank you! -
AWS ElasticBeanstalk failed to deploy Django/Postgres app
I'm having a hard time deploying my app built with Django, Postgres, DjangoQ, Redis and ES on AWS Elastic Beanstalk, using docker-compose.yml. I've used EB CLI (eb init, eb create) to do it and it shows the environment is successfully launched but I still have the following problem. On the EC2 instance, there is no postgres, djangoq and ec containers built like it says in the docker-compose file as below. Only django, redis and ngnix containers are found on the ec2 instance. The environment variables that I specified in the docker-compose.yml file aren't being configured to the django container on EC2, so I can't run django there. I'm pretty lost and am not sure where to even start to fix the problems here.. Any insight will be very much appreciated.. version: '3' services: django: build: context: . dockerfile: docker/Dockerfile command: gunicorn --bind 0.0.0.0:5000 etherscan_project.wsgi:application env_file: .env volumes: - $PWD:/srv/app/:delegated depends_on: - redis - db - es django-q: build: context: . dockerfile: docker/Dockerfile command: > sh -c "python manage.py makemigrations && python manage.py migrate && python manage.py qcluster" env_file: .env volumes: - $PWD:/srv/app/:delegated depends_on: - redis - db - django - es db: image: postgres:latest expose: - 5432 env_file: .env volumes: … -
i have a problem doing mutation to add product which has one to many relationship with another model in graphQL
my problem in i want to create a new internship from internship model and link it to cv in CV model with foreign key here is the models file class CV(models.Model): photo = models.ImageField(upload_to='CV/%Y/%m/%d/', null=True) headline = models.CharField(max_length=250) education = models.CharField(max_length=250) employment=models.CharField(max_length=250) class Internships(models.Model): employer=models.CharField(max_length=250) position=models.CharField(max_length=250) internship=models.ForeignKey(CV,on_delete=models.CASCADE,related_name="cv_internship") schema file class InternshipsType(DjangoObjectType): class Meta: model = Internships fields=("id","employer","position") class CVType(DjangoObjectType): class Meta: model = CV fields = ("id", "photo",'headline','education','employment','cv_internship') class InternshipsInput(graphene.InputObjectType): employer=graphene.String() position=graphene.String() class CvInput(graphene.InputObjectType): photo=graphene.String(required=True) headline=graphene.String(required=True) education=graphene.String(required=True) employment=graphene.String() internship=graphene.Field(InternshipsInput,id=graphene.Int()) class createCV(graphene.Mutation): cv=graphene.Field(CVType) class Arguments(): cv_data=CvInput() @staticmethod def mutate(root, info, cv_data): cv = CV.objects.create(**cv_data) return createCV(cv=cv) class createInternships(graphene.Mutation): class Arguments(): employer=graphene.String(required=True) position=graphene.String(required=True) internship=graphene.Field(InternshipsType) @classmethod def mutate(cls,root,info,employer,position,internship): internship=Internships(employer=employer,position=position) internship.save() return createInternships(internship=internship) i want to add an internship and link it to already existed cv with foreign key where i can write the foreign key in the createinternship class in the schema file here is aslo the query i write mutation{ addInternship(employer:"employername",position:"poition name"){__typename} } and here is the error mutate() missing 1 required positional argument: 'internship' -
Load data continuously even not connected to WebSocket
So, I have this data that needed to load before the connection. Is it possible to ready the data before the connection accept? so that the data is continuously sending even if not connected this is my consumer.py from . import eventhubreader class GraphConsumer(AsyncWebsocketConsumer): async def connect(self): event = eventhubreader.EventReader() async def cb(partition, events): data = events[len(events)-1] await self.send(json.dumps({'value': data.body_as_json()})) print(data.body_as_json()) await self.accept() while True: await eventHubReader.startReadMessage(iotconfig['connection_string'],iotconfig['consumer_group'],cb) this is the startReadMessage class EventReader: def __init__(self): data:str pass async def startReadMessage(self,iot_string,consumer,cb): eventHubString = self.iotConnToEventConvert(iot_string) consumerClient = EventHubConsumerClient.from_connection_string(eventHubString, consumer) async with consumerClient: try: await consumerClient.receive_batch(cb, starting_position="-1") except Exception as e: print(e) async def runIot(self,iot_string,consumer,cb): while True: await self.startReadMessage(iot_string,consumer,cb) this is the data def generateMockData(self,event): data = {} now = datetime.now() print(now) data["temperature"] = random.randint(23,25) data["tss"] = random.randint(5,8) data["vss"] = random.randint(1,4) data["bod"] = random.randint(1,7) data["doc"] = random.randint(8,13) data["cod"] = random.randint(5,12) data["ph"] = random.randint(2,13) data["turbidity"] = random.randint(1,5) data["conductivity"] = random.randint(1,7) data['datetime'] = now.strftime("%d/%m/%Y %H:%M:%S") return data -
How to Django queryset orderd_by in minimum time likes average max?
Info: I want to get queryset with order_by max like at minimum average time. In other words, In minimum time likes average max. Which have more average likes in less average time. current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") Model.objects.values( 'published_at', 'likes', ).aggregate( viewers=Avg(F('current_time') - Avg(F('published_at')) / F('likes')) ).order_by('-viewers')