Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Order_by a queryset more than once
I want to re-order my queryset after ordering it once. Is it possible? Here is my get_queryset method: def get_queryset(self): id_ordered_logs = BatchLog.objects.filter(batch__user__isnull=False)\ .order_by('-batch_id').distinct('batch_id') return id_ordered_logs I want to order this list by their created_at fields, this is what I want to do: def get_queryset(self): id_ordered_logs = BatchLog.objects.filter(batch__user__isnull=False)\ .order_by('-batch_id').distinct('batch_id') return id_ordered_logs.order_by('-created_at') I'd like to know if this is possible. Thanks and regards. -
can someone please kindly explain to me this lines of code in Django models
this is the model and I don't get the use of re in it import re from django.db import models class CategoryManager(models.Manager): I read the documentation on managers and I still don't get it def new_category(self, category): new_category = self.create(category=re.sub('\s+', '-', category).lower()) new_category.save() return new_category class Category(models.Model): category = models.CharField( verbose_name=_("Category"), max_length=250, blank=True, unique=True, null=True) objects = CategoryManager() what will the objects do here class Meta: verbose_name = _("Category") verbose_name_plural = _("Categories") def __str__(self): return self.category class Quiz(models.Model): title = models.CharField( verbose_name=_("Title"), max_length=60, blank=False) description = models.TextField( verbose_name=_("Description"), blank=True, help_text=_("a description of the quiz")) url = models.SlugField( max_length=60, blank=False, help_text=_("a user friendly url"), verbose_name=_("user friendly url")) category = models.ForeignKey( Category, null=True, blank=True, verbose_name=_("Category"), on_delete=models.CASCADE) random_order = models.BooleanField( blank=False, default=False, verbose_name=_("Random Order"), help_text=_("Display the questions in " "a random order or as they " "are set?")) max_questions = models.PositiveIntegerField( blank=True, null=True, verbose_name=_("Max Questions"), help_text=_("Number of questions to be answered on each attempt.")) answers_at_end = models.BooleanField( blank=False, default=False, help_text=_("Correct answer is NOT shown after question." " Answers displayed at the end."), verbose_name=_("Answers at end")) exam_paper = models.BooleanField( blank=False, default=False, help_text=_("If yes, the result of each" " attempt by a user will be" " stored. Necessary for marking."), verbose_name=_("Exam Paper")) single_attempt = models.BooleanField( … -
Get a list of users with a permission annotated as boolean
Is there a way to build a query to get a list of users with a boolean stating if they have a specific permission without the need to loop through the users and checking if they have the permission one by one -
Validating Multiple Files in Django forms.py
I am having a multiple file field, I want to validate the files and raise the errors in forms.py before the controls goes to is_valid() in view.py. forms.py class FileForm(forms.Form): filefield = forms.FileField( widget=forms.ClearableFileInput(attrs={'multiple': "true"}), ) def clean(self): print(self.cleaned_data['filefield']) #gives only one file I manage to get it work on view.py like below but I want to validate on forms.py def FileRender(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) if request.FILES.get('filefield') is not None: if form.is_valid(): fs = FileSystemStorage() uploaded_files = request.FILES.getlist('filefield') uploaded_file_url = [] for eachfile in uploaded_files: print(eachfile.name) print(eachfile.size) filename = fs.save(eachfile.name, eachfile) eachurl = fs.url(filename) # get the url of each file uploaded_file_url.append(eachurl) # adding urls to list # write command to save the link to model #allurls = '--'.join(uploaded_file_url) #print(allurls) # can save to db return render(request, 'MyApp/welcome.html', {'form': form, 'uploaded_file_url': uploaded_file_url}) return render(request, 'MyApp/welcome.html', {'form': form}) else: form = FileForm() return render(request, 'MyApp/welcome.html', {'form': form}) How to read all files from multiple input field in form.py and raise the validation error. -
Django-EAV realization for categories
I'm using https://github.com/DanielIndictor/django-eav2 eav repository for my online store. Faced a problem, I can't figure out how to pass attributes to the product depending on the category. When you select a category in the admin panel, the product should have the attributes of this category. Found such a data organization scheme, but I don't know how to implement it using this library. EAV database schema models.py from django.db import models import eav class Category(models.Model): name = models.CharField(max_length=40, verbose_name='Название') def __str__(self): return str(self.name) class Meta: verbose_name = 'Категория' verbose_name_plural = 'Категории' class Product(models.Model): name = models.CharField(max_length=40, verbose_name='Название') category = models.ForeignKey(Category, on_delete=models.PROTECT) def __str__(self): return str(self.name) class Meta: verbose_name = 'Товар' verbose_name_plural = 'Товары' eav.register(Category) eav.register(Product) admin.py from django.contrib import admin from eav.forms import BaseDynamicEntityForm from eav.admin import BaseEntityAdmin from .models import Product, Category # Register your models here. class CategoryAdminForm(BaseDynamicEntityForm): model = Category class CategoryAdmin(BaseEntityAdmin): form = CategoryAdminForm admin.site.register(Category, CategoryAdmin) admin.site.register(Product) -
How to retrive id of recently saved form in different def in django(Not using form)
I'm creating a three-step form and I'm saving on every step in a different model; I want to get an id of step1 data in different def for the second step I am not using form.py only views, HTML, model -
Django: Got got an unexpected keyword argument after Nested serializer
I have been working on RoutePrice Model and I tried to serialize data in nested serializer, before nested serializer it was fine working clean but I got type error after nested serializer. Here is Model and my serializer I have tried so far. class RoutePrice(BaseModel): bus_company_route = models.ForeignKey(BusCompanyRoute, on_delete=models.PROTECT) bus_type = models.ForeignKey(Category, on_delete=models.PROTECT) seat_price_for_travel_agent = AmountField() seat_price_for_user = AmountField() seat_price_for_foreigner = AmountField(null=True, blank=True) class Meta: default_permissions = () verbose_name = 'Route Price' verbose_name_plural = 'Route Prices' constraints = [ models.UniqueConstraint( fields=['bus_company_route', 'bus_type'], name='unique_route_price' ) ] and Here is how is serialized my data class AddRoutePriceSerializers(serializers.ModelSerializer): class Meta: model = RoutePrice fields = ( 'bus_type', 'seat_price_for_travel_agent', 'seat_price_for_user', 'seat_price_for_foreigner', ) class AddMultipleRoutePriceSerializers(serializers.Serializer): data = AddRoutePriceSerializers(many=True) I had my logic in usecases.py and views.py #usecases.py class AddRoutePriceUseCases(BaseUseCase): def __init__(self, serializer: AddMultipleRoutePriceSerializers, bus_company_route: BusCompanyRoute): self._serializer = serializer self._data = serializer.validated_data self._bus_company_route = bus_company_route def execute(self): self._factory() def _factory(self): print(self._data) self.route_price = RoutePrice(**self._data, bus_company_route=self._bus_company_route) try: self.route_price.full_clean() self.route_price.save() except DjangoValidationError as e: raise ValidationError(e.message_dict) #views class AddRoutePriceView(generics.CreateAPIView): """ Use this end-point to add route price to specific bus company route """ serializer_class = route_price_serializers.AddMultipleRoutePriceSerializers def get_bus_company_route(self): return GetBusCompanyRouteUseCase( bus_company_route_id=self.kwargs.get( 'bus_company_route_id' ) ).execute() def perform_create(self, serializer): return AddRoutePriceUseCases(serializer=serializer, bus_company_route=self.get_bus_company_route() ).execute() I got error saying Route RoutePrice() got … -
How to upload both json data and file using django rest framework
I'm making use of django default restapi. [This is the default api] [1]: https://i.stack.imgur.com/FhkuP.png before adding file , I upload the other fields in json format in the content textbox. Now I have file to upload. I've tested my code with postman, it works fine because it has provided file browse option. In api I don't have file browse option, How to add file browse option to default api or is there any way to give file in json itself(this didn't work as I gave file path in json). -
username from User is always giving anonymous
I am working on a website and when I try to access my username, it gives a null value Here's my models: User = get_user_model() class Contact(models.Model): user = models.ForeignKey( User, related_name='friends', on_delete=models.CASCADE) friends = models.ManyToManyField('self', blank=True) def __str__(self): if not self.user.username: return "Anonymous" return self.user.username class Message(models.Model): contact = models.ForeignKey( Contact, null=True, related_name='messages', on_delete=models.CASCADE) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): if not self.contact.user.username: return "Anonymous" return self.contact.user.username when i try to access it in for eg. the profile.js like this const mapStateToProps = state => { console.log(state.username) return { username: state.username } } it prints null this is also preventing me from authenticating cause it throws an error like this: react-dom.development.js:25058 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined I am stuck in this error for many days n would like some help -
How to fix table doesn't exist issue while importing Data from an external Database in Django?
I am creating a Django REST API where I have a read-only access to a particular PostgreSQL DB and I am writing all the Auth and other default tables to a local SQlite3 database. Following are my settings.py DATABASES = { 'prod': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'xx', 'USER': 'xx', 'PASSWORD': 'xx', 'HOST': 'xx', 'PORT': '5432', }, 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'auth.sqlite3', } } After doing this, I imported a table user_master from the external database into models.py and it created the following model: class UserMaster(models.Model): user_id = models.BigAutoField(primary_key=True) mobile_no = models.CharField(max_length=10) is_active = models.BooleanField(blank=True, null=True) access_token = models.CharField(max_length=220, blank=True, null=True) unique_id = models.CharField(unique=True, max_length=9, blank=True, null=True) status = models.BigIntegerField() is_md5_passcode = models.BooleanField(blank=True, null=True) access_code = models.CharField(max_length=200, blank=True, null=True) is_bcrypt_passcode = models.BooleanField(blank=True, null=True) created_date = models.DateTimeField() updated_date = models.DateTimeField() created_by = models.ForeignKey('self', models.DO_NOTHING, db_column='created_by', related_name='+') updated_by = models.ForeignKey('self', models.DO_NOTHING, db_column='updated_by', related_name='+') approved_on = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'user_master' I also created a router to allow read access from my prod db and write access only to me default db: class ProdRouter(object): def db_for_read(self, model, **hints): "Point all operations on prod models to 'proddb'" if model._meta.app_label == 'prod': return 'prod' return 'default' def db_for_write(self, model, **hints): … -
Is there a better way to parse a dynamic value of a Django Template into a Javascript file?
Is there a better method to retrieve the dynamic value 'bar' from the Django Template? index.html: <div id="foo" name="{{bar}}"></div> main.js: const foo = document.getElementById('foo') const bar = foo.name console.log(bar) output: bar -
Django - How to pass multiple selected values from selectpicker from template to views.py
I have a multiselect dropdown (select class="selectpicker" multiple) in my template. I want to transfer the selected values to my search function in views.py so that I can use those parameters to apply queries on my database table and then route the user to Listings page based on search parameters selected. Please see below my code. Can you please assist as to what I am doing wrong: Template file: Colony (All) {% for key,value in colony_choices.items %} {{ value }} {% endfor %} views.py: if 'colony[]' in request.GET: {% for colony in request.GET.getlist('colony[]') %} if colony: str = str + "," + colony {% endfor %} queryset_list = queryset_list.filter(colony__in=[str]) Once queryset_list is formed, I am passing that as context to my Listings page which is working fine. Can someone please suggest what needs to be changes in template or views.py file. -
Using Dropdown values to set user ranks on creation
I have a user creation form in my Django web application. I am able to create a user normally. I have a model in my application called user_type, which has the is_admin field, is_manager field and the user field linked to the User Foreign Key. I have added a dropdown in my user creation form to enable the Admin create a user and as well assign the user_type of the user using the dropdown. I am now confused of how to grab the admin choice and enable the user_type depending on that. models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) # CUSTOM USER FIELDS firstname = models.CharField(max_length=30, blank=True, null=True) lastname = models.CharField(max_length=30, blank=True, null=True) telephone = models.IntegerField(blank=True, null=True) address = models.CharField(max_length=300) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) class user_type(models.Model): is_admin = models.BooleanField(default=False) is_manager = models.BooleanField(default=False) user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): if self.is_manager == True: return User.get_email(self.user) + " - is_manager" else: return User.get_email(self.user) + " - is_admin" views.py def AddUser(request): if … -
How to prevent staff users from editing/deleting superuser in django
I want to be able to allow certain staff users the rights to add other users and staff but what seems weird to me is that 1) a staff member can just change their own privileges to superuser or just make a new user and grant superuser privileges to them. 2) delete a superuser or revoke their superuser status Some staff users should be able to modify/create/delete users but they should not be able to delete super users nor assign permissions to themselves or other users that they do not have the permission themselves. This has always been logic I have incorporated into my user systems that I've written in PHP and I was just wondering if there was a way to change these settings in Django as I really like Python/Django (I'm just beginning to learn it) and can see myself migrating away from PHP. But part of the beauty for me lied in the admin panel and if that is something that cannot be changed, that's kind of cringe-worthy. It reminds me of a restaurant POS system that I used to use when I was a GM. As the GM, I had powers that shift managers did not … -
Getting model name in Django template
I am trying to do a search over many data models in Django to my site. Now I have code like this in views. class Search(ListView): template_name="search.html" context_object_name="result_serch_all" paginate_by = 10 def get_queryset(self): news = Articles.objects.filter(title__icontains=self.request.GET.get("q")) docs = Doc.objects.filter(name_doc__icontains=self.request.GET.get("q")) query_sets = list(chain(news, docs)) return query_sets def get_context_data(self, *args, **kwargs): paginator = Paginator(self.get_queryset(), 5) context = super().get_context_data(*args, **kwargs) context["q"] =f'q={self.request.GET.get("q")}&' print(context['result_serch_all']) return context In the template, I output like this {%for el in result_serch_all%} <div> {{el}} </div> {% endfor %} How can the output in the template be divided into blocks?So that in front of all found articles there is an inscription Found in the news section. Before the documents Found in the documents section`? I found this option. In my model im add def get_my_model_name(self): return self._meta.model_name and in the template I check {% if el.get_my_model_name == 'articles' %} Maybe there is some standard way in Django? -
coercing to Unicode: need string or buffer, FieldFile found
models.py def document_file_name(instance, filename): char_set = string.ascii_uppercase + string.digits dat = ''.join(random.sample(char_set*6, 12)) x = str(instance.created_by_id) + '/' + dat + '_' + re.sub(r'[^a-zA-Z0-9-_.]', r'_', filename) return 'documents/' + str(instance.created_by_id) + '/' + dat + '_' + re.sub(r'[^a-zA-Z0-9-_.]', r'_', filename); class UploadDocument(models.Model): document = models.FileField(upload_to=document_file_name, blank=True, null=True) other_doc = models.ForeignKey("doc.OtherDocuments") views.py def opportunity_document_add(request, opportunity_id): c = setup_context(request) other_documents = get_object_or_404(OtherDocuments, pk=opportunity_id) c['other_documents '] = other_documents c['other_documents_id'] = other_documents document = UploadDocument(other_doc=other_documents ) errors = {} if request.method == "POST": document.type = request.POST.get('type') if('document' in request.FILES): document.document = request.FILES['document'].read() file = document.document bucket = settings.AWS_STORAGE_BUCKET_NAME s3_client = boto3.client('s3') object_name = None with open(file, 'rb') as f: s3.upload_fileobj(f, bucket, file) document.save() Here i am getting the error "coercing to Unicode: need string or buffer, FieldFile found" -
Preference to choices based on a value of another model in Django?
I declared my choice as STATUS_CHOICES = ( ('A', 'available'), ('N', 'new'), ('R', 'reserved'), ('S', 'sold-out'), ) And i use this preferences in my Item model to show the current status of my item "status = models.CharField(choices=STATUS_CHOICES, max_length=1)" My problem here is that based on the "stock_no" category in my item model "stock_no = models.CharField(max_length=10)" The product status should automatically change from "Available to Reserved" or "Available to Sold-Out" can some one please help me with the logic for this issue Thank you. -
How to add some cutom code to post method in django rest framework
I am new to django rest framework. I was trying to build a API where I want to edit the POST method so that I could execute some actions and change some data from the POST body. I tried to follow some documentations and Guide from django rest framework website but didnt followed any. Please help me. Here I need to set some values for some fields that are going to be saved in the database. views.py from .models import LoginActivity from .serializers import LoginActivitySerializers class LoginActivity(viewsets.ModelViewSet): queryset = LoginActivity.objects.all() serializer_class = LoginActivitySerializers urls.py from django.urls import path, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'LoginActivity', views.LoginActivity, basename='LoginActivity') # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. appname='api' urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] serializers.py from rest_framework import serializers from .models import LoginActivity class LoginActivitySerializers(serializers.HyperlinkedModelSerializer): class Meta: model = LoginActivity fields = ('id', 'user_id', 'datetimelog', 'device_os', 'device_token', 'device_model') Please Help me. -
Create a related object in django
I have a model Inventory related to another model Product class Inventory(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) owner = models.ForeignKey(User, on_delete=models.CASCADE) whenever I create a "Product" I want to create a blank entry of "Inventory" as well. How can I do that? Views.py class ProductCreateAPIView(CreateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = ProductSerializer parser_classes = (FormParser, MultiPartParser) def post(self, request, *args, **kwargs): owner = request.user.pk d = request.data.copy() d['owner'] = owner serializer = ProductSerializer(data=d) if serializer.is_valid(): serializer.save() print("Serializer data", serializer.data) Inventory.objects.create(product=serializer.data['id'], quantity = 0, owner = owner) <= Will this work? return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
How to read data from an External Server and apply migrations on a local Db file in Django?
My situation is as follows: I have an external database with a read-only access from where I want to import my Data Models, which I did using: python manage.py inspectdb > models.py After I have handled all my exceptions after importing the models, when I try to migrate, it asks for permission to write to the external db to create extra tables for running the django project, like admin, auth, contenttypes, sessions How do I continue reading data from my external database for running my REST API while applying the required migrations for Auth and other important tables to another locally stored database? Following is the error I'm getting: LINE 1: CREATE TABLE "django_migrations" ("id" serial NOT NULL PRIMA... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\migrations\recorder.py", line 67, in ensure_schema editor.create_model(self.Migration) File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\backends\base\schema.py", line 307, in create_model self.execute(sql, params or None) File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\backends\base\schema.py", line 137, in execute cursor.execute(sql, params) File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 99, in execute return super().execute(sql, params) File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, … -
bulk-updating a bunch of many-to-many fields proves to be expensive, given my constraints (Django Rest Framework)
If you've noticed the discord roles system or the structure, each role has an unique position which determines which role is greater or lesser. From official documentation So, when a new role is created, if the role's position overlaps with an existing role's position, all the roles below the new role are shifted down (position value is changed by 1). Taking inspiration from this, I have developed my own roles system with django-rest-framework. Here's code from the backend: class Role(models.Model): """ Represents a Role object. Every parent can have it's own roles. Roles have their own: - Hex Color Code [Integer Representation] - Name [&] - Permissions. Role permissions for individual datasheets override global parent permissions. Parent IS NULL indicates the parent is for the whole parent. """ objects = models.Manager() id = models.BigAutoField(primary_key=True, db_index=True, editable=False, auto_created=True) name = models.CharField(max_length=512, db_index=True) hex_color_code = models.IntegerField(db_index=True) position = models.IntegerField(db_index=True) permissions = models.ManyToManyField(Permission) parent = models.ForeignKey('api_backend.DataSheet', on_delete=models.CASCADE, db_index=True) cluster = models.ForeignKey('api_backend.DataSheetsCluster', on_delete=models.CASCADE, db_index=True, editable=False) created_at = models.DateTimeField(auto_now=True, editable=False, db_index=True) REQUIRED_FIELDS = [name, cluster, position] Serializer for the same: class RoleSerializer(serializers.ModelSerializer): """ A serialized Role object. Roles have an array of permissions. When roles are given to members in clusters, these roles determine the … -
detect related model or create in django
I have two models # models.py class Expert(models.Model): company = models.ForeignKey( Company, on_delete=models.SET_NULL, blank=True, null=True ) first_name = models.CharField(blank=True, max_length=300) class Meeting(models.Model): expert = models.ForeignKey(Expert, on_delete=models.SET_NULL, blank=True, null=True) start = models.DateTimeField(db_index=True, blank=True, null=True) timezone = TimeZoneField(default="America/New_York") What's the best way to write a view that will create a Meeting with an Existing Expert in the database OR create a new Expert and associate it with the new Meeting? my forms # forms.py class ExpertForm(forms.ModelForm): first_name = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "Name"})) class Meta: model = Expert fields = [ "first_name", "company", ] widgets = { "company": autocomplete.ModelSelect2( url="company_private", attrs={ "data-placeholder": "Company", "data-delay": "250", "data-tags": "true", }, ) } class MeetingForm(forms.ModelForm): class Meta: model = Meeting fields = [ "start", "timezone", "expert", ] class MeetingDateAMPMForm(forms.ModelForm): """Meeting Form with support for calendar and am/pm format.""" date_format = "%m/%d/%Y %I:%M %p" # django_date_format = "%m/%d/%Y %H:%M" start = forms.DateTimeField( input_formats=[date_format], widget=DateTimePickerInput(format=date_format), ) class Meta: model = Meeting fields = [ "start", "timezone", "expert", ] def clean_expert(self): data = self.cleaned_data["expert"] if not data: raise ValidationError("An expert is required to create a meeting.") return data my view thusfar # views.py def meeting_expert_create(request): logger.info("meeting_expert_create: running") est_offset = datetime.timedelta(hours=5) if request.method == "POST": meeting_form = MeetingDateAMPMForm(request.POST) expert_form = ExpertForm(request.POST) params … -
Implementation of SSO to my application using Django
I have appX, appY that is build by my organization which is used by other organizations. So now we have plan of implementing SSO to our application. I know my applications will be Service Providers. My question: What should be my approach in reaching to many customers IdP with my SP? Apart from SAML protocol any other suggestions? This would be helpful. -
Hey i want to sum up Total Income and Total Indirect Income Using Jquery How can i do that?
Hey i want to sum up total income and total indirect income. This total values in html table comes using jquery by providing a class. But now i want to sum up two table total values in a single variable and put in a new html table. The new html table looks like we have a column total (income+indirect income) = variable How can i do that using Jquery.Here you can see that the values of total amount column are sum up and lies in the footer on every table. But now i want to sum up two table values in a single variable and that new variable i want to put in a new html table on a same page. $(document).ready(function() { var total_1 = 0; $('.income-amount').each(function(i, obj) { total_1 += parseInt($(obj).text()); }); $('#income-total').text(total_1.toFixed(1)); }); This Jquery i use in Html table for total amount column sumup. Here i also provide my html table. <table id="example" class="table table-striped table-bordered table-responsive-xl"> <caption style="caption-side:top; text-align: center;"><h3>Income</h3></caption> <thead class="thead-dark"> <tr> {# <th>S No.</th>#} <th>Particulars</th> <th>Description</th> <th>Total Amount</th> </tr> </thead> <tbody> {% for item in all_profit %} {% if item.category.under == "Income" %} <tr> {# <td>{{ }}&nbsp;</td>#} <td>{{item.category}}</td> <td>{{item.category.desc}}</td> <td class='income-amount'>{{ item.balance }}&nbsp;</td> … -
django annotate on large data (SLOW) - an alternative?
I have 2 models: Follower has 10M queries class Follower(models.Model): identifier = models.BigIntegerField( _("identifier"), unique=True, null=False, blank=False) username = models.CharField( _("username"), max_length=250, null=True, blank=True) Actions has 5M queries class ActionModel(models.Model): target = models.ForeignKey(Follower, verbose_name=_("Target"), on_delete=models.CASCADE) # username is_followed_back = models.BooleanField(_("Followed Back"), null=True, blank=True) # is target followed back user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, editable=False ) # django user that performed the action Each time I get into Admin panel at Follower I want to count the number of actions per follower per user, and the follow_back field is True : def get_queryset(self, request): ... actionmodel__user = Q(actionmodel__user=request.user) qs = qs.annotate( been_followed_count=Count('actionmodel', filter=actionmodel__user, distinct=True) ).annotate( follow_back_count=Count( 'actionmodel', filter=(actionmodel__user & Q(actionmodel__is_followed_back=True)), distinct=True ) ) IT WORKS BUT IS VERY SLOW ! I guess it filter for each one out of the 10M followers it actions ... so it runs 10M X 5M times ? What is the alternative? I can't store the "been_followed_count" and "follow_back_count" on the Follower model since it common for all django users, so can I somehow store those value instead or recalculate it each get_queryset ?