Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
sending mail works with mailtrap but not with an outlook server or other
I made a contact form, I tested with the mailtrap service and it works I receive the messages well. But when I put the smpt parameters for a real mail account I have this error message SMTPRecipientsRefused at /contact/ {'info@mysite.net': (550, b'relay not permitted: you must be authenticated to send messages')} the smtp server and the mail account is on the host alwasdata.net, but I tested with an outloock account it's the same thing always this same error. it seems to come from the line in the contact method: message, 'info@mysite.net', ['info@othersite.net'], fail_silently=False, in settings.py i have this config EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = "info@mysite.net" EMAIL_USE_TLS = True EMAIL_USE_SSL = False EMAIL_HOST = 'smtp-blablabla.net' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 in a views.py def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = "Message d'un visiteur sur votre site" body = { 'Nom': form.cleaned_data['first_name'], 'Tel': form.cleaned_data['tel'], 'Email': form.cleaned_data['email'], 'Message':form.cleaned_data['message'], } message = "\n".join(body.values()) try: send_mail( subject, message, 'info@mysite.net', ['info@othersite.net'], fail_silently=False, ) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('/') form = ContactForm() return render(request,'pages/email_form.html',{'form':form}) the forms.py from django import forms class ContactForm(forms.Form): first_name = forms.CharField(max_length=100, required=True) tel = forms.CharField(max_length=15, required=True) email = forms.EmailField(required=False) message = forms.CharField(widget=forms.Textarea, required=True) -
install postgresql extension before pytest set up database for django
I need to install citext extension to my postgresql database for django project. For the project itself it went smoothly and works great via migrations, but my pytest is configured with option --no-migrations, so pytest create database without running migrations. How can i make pytest to install citext postgres extension before tables are created? Currently i'm getting - django.db.utils.ProgrammingError: type "citext" does not exist while pytest trying to create table auth_users sql = 'CREATE TABLE "auth_user" ("id" serial NOT NULL PRIMARY KEY, "password" varchar(128) NOT NULL, "last_login" timestamp ...T NULL, "is_active" boolean NOT NULL, "date_joined" timestamp with time zone NOT NULL, "email" citext NOT NULL UNIQUE)', params = None ignored_wrapper_args = (False, {'connection': <django.contrib.gis.db.backends.postgis.base.DatabaseWrapper object at 0x7fb313bb0100>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0x7fb30d9f8580>}) I tried to use django_db_setup fixture, but i did not figure out how to change it, because something like this @pytest.fixture(scope="session") def django_db_setup( request, django_test_environment, django_db_blocker, django_db_use_migrations, django_db_keepdb, django_db_createdb, django_db_modify_db_settings, ): """Top level fixture to ensure test databases are available""" from django.test.utils import setup_databases, teardown_databases setup_databases_args = {} if not django_db_use_migrations: from pytest_django.fixtures import _disable_native_migrations _disable_native_migrations() if django_db_keepdb and not django_db_createdb: setup_databases_args["keepdb"] = True with django_db_blocker.unblock(): from django.db import connection cursor = connection.cursor() cursor.execute("CREATE EXTENSION IF NOT EXISTS … -
Unable to login even after entering correct credentials
I have created a seperate app for user account management which handels registration, login and logout. However, after successful signup, I'm unable to login even after using the correct credentials provided during signup. Here are the required code for the review: models.py `from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, first_name, last_name, username, email, password=None): if not email: raise ValueError('Email is required.') if not username: raise ValueError('Username is required.') user = self.model( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name,`your text` ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, first_name, last_name, username, email, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, first_name=first_name, last_name=last_name, ) user.is_admin = True user.is_active = True user.is_staff = True user.is_superuser = True user.save(using=self.db) return user class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) username = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=100, unique=True) phone_number = models.CharField(max_length=50) # required date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_superadmin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, add_label): return True` forms.py `from crispy_forms.helper import FormHelper from django import forms from .models import Account class RegistrationForm(forms.ModelForm): first_name = … -
enctype='multipart/form-data' is not storing images in django?
I wanted to save text and images in my database in django but when i used enctype='multipart/form-data' it is not storing the image. When i do it without enctype='multipart/form-data' it is storing the name of image this is my index.html ` <form method="POST" action="/index" enctype='multipart/form-data'> {% csrf_token %} <div>Dish name: <input name="dish_name" type="text" placeholder="Dish name"></div> <div>Dish category: <input name="dish_category" type="text" placeholder="Dish category"></div> <div>Dish size: <input name="dish_size" type="text" placeholder="Dish size"></div> <div>Dish price: <input name="dish_price" type="text" placeholder="Dish price"></div> <div>Dish description: <input name="dish_description" type="text" placeholder="Dish description"></div> <div>Dish image: <input name="dish_image" type="file"></div> <button type="submit" class="btn btn-success">Submit</button> </form> this is my views.py def index(request): if request.method == "POST": dish_name = request.POST.get('dish_name') dish_size = request.POST.get('dish_size') dish_price = request.POST.get('dish_price') dish_description = request.POST.get('dish_description') dish_image = request.POST.get('dish_image') dish_category = request.POST.get('dish_category') item = dish(dish_name = dish_name, dish_size = dish_size, dish_price = dish_price, dish_description = dish_description,dish_category=dish_category, dish_image = dish_image, dish_date = datetime.today()) item.save() dishs = dish.objects.all() params = {'dish': dishs} return render(request, "card/index.html", params) this is my models.py class dish(models.Model): dish_id = models.AutoField dish_name = models.CharField(max_length=255, blank=True, null=True) dish_category = models.CharField(max_length=255, blank=True, null=True) dish_size = models.CharField(max_length=7, blank=True, null=True) dish_price = models.IntegerField(blank=True, null=True) dish_description = models.CharField(max_length=255, blank=True, null=True) # dish_image = models.ImageField(upload_to="images/", default=None, blank=True, null=True) dish_image = models.ImageField(upload_to="media/", default=None, blank=True, null=True) #here … -
How to monitor a thread in python?
I'm having a kafka consumer which is running in a thread in my django application, I want to apply some monitoring and alerting on that thread. So how can I add thread monitoring (check state if it is alive or dead) and if thread is dead then need to raise an alert. I have tried monitoring by creating scheduler which runs every 10 mins and calls thread.is_alive() method. But the problem is the scheduler is running in a different process and unable to access main process' s thread. So how can I resolve this? -
Two models with one-to-many into single JSON dict
I have two models for 'PO Header' and 'PO Item' data like this: class po(models.Model): po_number = models.CharField(max_length=16, null=True) buy_org = models.CharField(max_length=20, null=True) supplier = models.CharField(max_length=16, null=True) class poitm(models.Model): po = models.ForeignKey(po, on_delete=models.CASCADE, related_name='poitm') po_li = models.CharField(max_length=6, null=True) matnr = models.CharField(max_length=16, null=True) quantity = models.DecimalField(decimal_places=6, max_digits=16, null=True) I try to create a view that returns a json object like this: [{'po_number':'45000123','buy_org':'Org1','supplier':'Org2','itemlist':[{'po_li':'010','matnr':'123456','quantity':'12'},{'po_li':'020','matnr':'123457','quantity':'8'}]},{'po_number':'45000124','buy_org':'Org1','supplier':'Org2','itemlist':[{'po_li':'010','matnr':'123235','quantity':'15'},{'po_li':'020','matnr':'123499','quantity':'24'}]} ] In principle a list of purchase orders with each purchase order containing a list of purchase order items. I managed to create queryset containing the data like I need it but for performance reasons when using datatables.net with dom data I need to return the data in json format instead of looping through the queryset in the html template. def purchaseorders(request): polist=purchaseOrder.objects.all() itemlist=poItem.objects.all() for poentry in polist: poentry.itemlist=itemlist.filter(po_id=poentry.id) return render(request, 'purchaseorders.html', {"poitems":polist}) This seems to create a queryset with each object of a queryset. This then gives me a problem when I try to serialize it to json. Only the fields from the outer queryset are in the json result. I looked and tried for two solid days, turning in circles now, please help. -
How to get data from database, whenever database is updated in database Caching in Django [closed]
When i hit API every time data is fetching from database caching, even though database is updated(add or remove). How to communicate with cache and database, when changes are made in database -
Replace Django Admin Login page
I need to replace the Django Admin Login page. The reason for that is that I've added some extra authentication at my own login page, however, I don't know how to override the login on the admin site. -
Django authentication password returning False
I'm trying to create an authentication system using Django with a custom backend and user class, but every time I try to authenticate with an existing user and password in my Postgresql database the check_password() function always returns False and I can't proceed. Here's the code for the UserBackend on backends.py from django.contrib.auth.backends import ModelBackend from .models import user class UserBackend(ModelBackend): def authenticate(self, **kwargs): username = kwargs['username'] password = kwargs['password'] print('user: ', username) print('pass: ', password) #try: user_ = user.objects.get(username=username) try: print(user_.check_password(password)) if user_.check_password(password) is True: #Here check_password() is always false return user_ except user.DoesNotExist: pass def get_user(self, user_id): try: return user.objects.get(pk=user_id) except user.DoesNotExist: return None views.py def signin(request): now = datetime.now() if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = UserBackend.authenticate(ModelBackend(),username=username, password=password) if user is not None: #auth.login(request, user) return redirect('/index') else: messages.info(request, 'invalid username or password') return redirect("/signin") else: return render(request,'signin.html') return render(request, 'signin.html') models.py class user(AbstractBaseUser): id = models.AutoField(primary_key=True) username = models.TextField() real_name = models.TextField() email = models.TextField() password = models.TextField() description = models.TextField() last_login = models.DateField() created_at = models.DateField() class Meta: managed = False db_table = 'user' def __str__(self) -> str: return self.username what am I doing wrong? -
How to search inside json file with redis?
Here I set a json object inside a key in a redis. Later I want to perform search on the json file stored in the redis. My search key will always be a json string like in the example below and i want to match this inside the stored json file. Currently here i am doing this by iterating and comparing but instead i want to do it with redis. How can I do it ? rd = redis.StrictRedis(host="localhost",port=6379, db=0) if not rd.get("mykey"): with open(os.path.join(BASE_DIR, "my_file.josn")) as fl: data = json.load(fl) rd.set("mykey", json.dumps(data)) else: key_values = json.loads(rd.get("mykey")) search_json_key = { "key":"value", "key2": { "key": "val" } } # here i am searching by iterating and comparing instead i want to do it with redis for i in key_values['all_data']: if json.dumps(i) == json.dumps(search_json_key): # return # mykey format looks like this: { "all_data": [ { "key":"value", "key2": { "key": "val" } }, { "key":"value", "key2": { "key": "val" } }, { "key":"value", "key2": { "key": "val" } }, ] } -
i have a basic register api,however, it seems to be throwing this error, HTTP_201_CREATED' not found
i am getting this error ,i tried to convert fields variable in serializers.py to my_fields but it cannot be changed,also i tried to convert values of fields variable in list but of no use**.it was working at first but i dont know what seems to be the problem Internal Server Error: /api/auth/signup Traceback (most recent call last): File "/home/technogetic/Documents/Django Rest Framework/VPAProject/firstapp/views.py", line 97, in post return Response[{'msg':'Registration Successfull, A Verification code has been send to your Email'}, status.HTTP_201_CREATED] AttributeError: 'tuple' object has no attribute 'HTTP_201_CREATED' views.py class UserRegistrationView(GenericAPIView): serializer_class = UserRegistrationSerializer renderer_classes = [UserRenderer] def post(self, request, format=None): confirm_password = request.data.get('password1') #Request the Email from the user) # confirm_password = request.data.get('password1') #Request the Email from the user email = request.data.get('email') #Request the Email from the user username = request.data.get('username') # Request the username from the user password = request.data.get('password') # Request the password from the user first_name = request.data.get('first_name') # Request the first name from the user last_name = request.data.get('last_name') # Request the last name from the user if not email or not username or not password or not first_name or not last_name: # check the parameters for the email,username,password,firstname,lastname. return Response({'msg': 'Invalid parameters'}) pass_bool = Validate_Password(password) # Validate the … -
How to configure Django application deployed with Gunicorn with a front NGINX server, through docker compose?
I am finding difficulty in understanding the mistake in the following setup which attempts to serve a django-gunicorn application server with nginx. (Am not yet concentrating on static assets) Docker compose file # Mentioning which format of dockerfile version: "3.9" # services or nicknamed the container services: # web service for the web web: build: . # Add additional commands for webpack to 'watch for changes and bundle it to production' command: gunicorn --bind unix:/run_socket/gunicorn.sock StockWhiz.wsgi:application # Below command for using gunicorn to serve. volumes: - type: bind source: ./stockwhiz-web target: /code - type: bind source: ./run_socket target: /run_socket depends_on: - db environment: - "DJANGO_SETTINGS_MODULE=StockWhiz.settings.local" db: image: postgres:14-bullseye # volumes: - postgres_data:/var/lib/postgresql/data/ # unsure of what this environment means. environment: - "POSTGRES_HOST_AUTH_METHOD=trust" nginx: image: nginx:stable restart: always volumes: - ./run_socket:/run_socket - ./config/nginx/:/etc/nginx/conf.d/ ports: - "80:80" depends_on: - web # Volumes set up volumes: postgres_data: NGINX config # Note in our docker compose it's typically located at etc/nginx/conf.d/ # Which are automatically copied on to the nginx.conf file at etc/nginx upstream gunicorn_application { server unix:/run_socket/gunicorn.sock; } server{ listen 80; server_name www.stockwhiz.in; error_log stderr warn; access_log /dev/stdout main; location / { include /etc/nginx/uwsgi_params; uwsgi_pass gunicorn_application; } } Logs Some of the logs … -
Which database is best for python? [closed]
I am confusing to choose the database. Mysql or mongodb or sqllite -
In django, how to annotate(group by) date from a datetime field with MYSQL
Defined as class Data(models.Model): created_at = models.DateTimeField(default=timezone.now) number = models.IntegerField(default=1) And the requirement is to get sum group by date from created_at and I was using. qs = Data.objects.values('created_at__date').annotate(sum=Sum('number')) The above query works fine with sqlite3, but it failed with MySql. In MySql, it returns single result <QuerySet [{'created_at__date': None, 'sum': 100}]> Excepted: <QuerySet [ {'created_at__date': datetime.date(2021, 7, 12), 'sum': 50}, {'created_at__date': datetime.date(2021, 7, 13), 'sum': 50} ]> -
How to access properties of one-to-Many relationships in Django templates?
I am very new to Python & Django. I am building a personal diary with pretty simple properties such as Months and Entries. models.py class Month(models.Model): id = models.AutoField(primary_key=True) month_name = models.CharField(verbose_name="Month", max_length=20, unique=True) year_number = models.IntegerField(verbose_name="Year") featured_img = models.ImageField(verbose_name="Featured", upload_to='diary/featured_img', default=False) class Meta: verbose_name = "Month" ordering = ['-year_number', 'month_name'] def __str__(self): return '%s, %s' % (self.month_name, self.year_number) class Entry(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=200) content = models.TextField() month = models.ForeignKey('Month', on_delete=models.RESTRICT, null=True) img = models.ImageField(verbose_name="Image", upload_to='diary/entry_img', default=False) date_created = models.DateTimeField(verbose_name="Date", default=timezone.now) def __str__(self): return self.title class Meta: verbose_name_plural = "Entries" ordering = ['-date_created'] I am trying to build a simple webpage which displays the Months in list form and when I click on the month I get the entries in detail view. I completed the first step but I cannot figure out how to access the one-to-many relationships between Month and Entry model in Django templates. What I want to do is to display a page with all the Month model objects and when a user clicks on a specific month say "December", Django returns all the entries which have the month object defined as December. This worked fine in the admin site where I inserted TabularInLine … -
Is it correct to use Celery in Kafka Consumer?
I am doing some long-running tasks in Kafka Consumer. I want to know that I am doing right or wrong? I am using Kafka Consumer to consumer messages from another server and messages are processing as I want. I am putting the received message in the Celery queue. And all is working well. Does Here need Celery? Or Kafka will handle it as a queuing system? _consumer = KafkaConsumer(KAFKA_TOPIC, bootstrap_servers=['{}:{}'.format(HOST, PORT)],auto_offset_reset="earliest", value_deserializer=lambda x: ReadHelper().json_deserializer(x), group_id="mygroupZ1") for msg in _consumer: payload = msg.value print("data fetched payload------------------") long_running_task.delay(payload) # Does here need Celery task to put in? -
Cannot send javascript post data to django view
I have a function in javascript in which I am trying to a very simple key value pair of data through a post request into the same view in which the webpage is rendered from. I have a form in the same template/webpage HTML that is able to send post data to the view just fine, however the javascript is unable to do so and I am left with null data in the view. Javascript: ` postAccount(); async function postAccount() { accountPromise = getAccount().then(accounts => { return accounts[0]; }) //This function call to retrieve the account will be put here until I can figure out a way to //pull the address with the user pressing login ONLY IF the the user has already connected theyre metamask. account = await accountPromise; var data = new FormData(); data.append("address", account.toString()); console.log("address=" + account.toString()); let post = new XMLHttpRequest(); post.open("POST", "{% url 'index' %}", true); post.setRequestHeader('Content-Type', 'application/json'); post.send(data); } Django view: @csrf_exempt def index(request): context = {} usernameInput = None; address = None; if (request.method == 'POST'): usernameInput = request.POST.get("username_input") address = request.POST.get("address") print(usernameInput, address) if (usernameInput != None and address != None): user = generalUser(address = str(address), username = usernameInput, lastLogin = timezone.now()) … -
User data not updating in admin panel and forms django
When I try to update user data (in admin panel or form) it does nothing and give 0 errors. In the admin panel, it says it updated, but data stays the same. Here's my model.py: https://pastecode.io/s/jx4jpt0x -
Multi file upload with other info in Django Rest Framework
I am going to create multi file upload api in django rest framework. Each file has file description field. So I need to upload bulk files and files description data at the same time. files = request.FILES.getlist('files[]') files_description = json.loads(request.data.get('files_description')) I can create File model instances by looping files_description. The issue is, file field is optional. So above files, files_description length can be different, since file field can be optional. How can I match file field and file description? -
How should I handle package dependency conflicts, especially in Django?
I've been trying to implement BERTopic inside my Django project. However, the dependencies of BERTopic conflicts with my existing numpy version: When I run !pipdeptree -p bertopic in jupyter notebook, I get this output: * tensorflow-gpu==2.3.0 - numpy [required: >=1.16.0,<1.19.0, installed: 1.21.6] I was trying to use BERTopic in views.py More than wanting to solve this specific issue with numpy, I would like to know how to solve any conflicts between package dependencies. -
I don´t get to see my mistake. Why do I get this error? raise RequestsJSONDecodeError
......................... ....................... ...................... When I execute, python py_client/details.py, I get: raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0) What´s going wrong here? detail.py import requests endpoint = "http://localhost:8000/api/products/1" get_response = requests.get(endpoint) print(get_response.text) this is urls.product from django.urls import path from . import views urlpatterns = [ path('<int:pk>/', views.ProductDetailAPIview.as_view()), path('', views.ProductCreateAPIview.as_view()), ] I am getting error Expecting value: line 1 column 1 (char 0) It doesn´t work in the browser either. It says: Page not found (404) this is urls.cfehome from django.contrib import admin from django.urls import path from django.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include("new_api.urls")), path('/api/products/', include("products.urls")) ] this is my view in the app products from rest_framework import generics from .models import Product from .serializers import Productserializers class ProductDetailAPIview(generics.RetrieveAPIView): queryset = Product.objects.all() serializer_class = Productserializers class ProductCreateAPIview(generics.CreateAPIView): queryset = Product.objects.all() serializer_class = Productserializers -
Blending the rendering of DataTableView and a standard view in Django
I'm pretty new to django and have been experimenting with some of the code I want to build a form that starts with a parent record, lists the children of that record, and then when I click on a child (or a button in the row of that child) shows the children under that in a datatableview object. phew It should look a little like this: So the dataset is the primary object into the view, and the tables are a datatables filtered by the dataset id, which all works fine... but how do I get the {{ datatable }} to render in context? The current view code is pretty basic - this is initially all just for display. def datasetview(request, datasetid): dataset = get_object_or_404(DataSet, pk=datasetid) context = { 'dataset': dataset, } return render(request, 'data/dataset_view.html', context) within the html template, I render the table list with: {% for datatable in dataset.datatables.all %} {% if not datatable.deleted %} <tr> <td class="p-1 align-middle">{{ datatable.tablename }}</td> <td class="p-1 align-middle"><button type="button" class="btn btn-outline-primary" onclick="fill_attribute_table({{ datatable.datatableid }})">Edit</button></td> </tr> {% endif %} {% endfor %} I've been able to render the dataviewtable as a generic page using the demo code provided at pypi.org/project/django-datatable-view (that's how I … -
404 error while implementing async function
detail.html {% if request.user.is_authenticated %} <form class="like-forms d-inline" data-book-id="{{ book.pk }}" data-review-id="{{ review.pk }}"> {% csrf_token %} <h4> {% if request.user in review.like_users.all %} <button type="submit" id="btn-like-{{ review.pk }}" class="btn-none bi bi-emoji-heart-eyes"></button> {% else %} <button type="submit" id="btn-like-{{ review.pk }}" class="btn-none bi bi-emoji-angry"></button> {% endif %} </h4> </form> {% endif %} <!-js--> <script> const likeForms = document.querySelectorAll('.like-forms') const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value likeForms.forEach((form) => { form.addEventListener('submit', function (event) { event.preventDefault() const reviewId = event.target.dataset.reviewId const bookId = event.target.dataset.bookId axios({ method: 'post', url: `/detail/${bookId}/like/${reviewId}/`, headers: {'X-CSRFToken': csrfToken}, }) .then(response => { const isLiked = response.data.isLiked const likeBtn = document.querySelector(`#btn-like-${reviewId}`) console.log(isLiked) if (isLiked === true) { likeBtn.classList.add('bi-emoji-heart-eyes') likeBtn.classList.remove('bi-emoji-angry') } else { likeBtn.classList.add('bi-emoji-angry') likeBtn.classList.remove('bi-emoji-heart-eyes') } }) .catch(error => { console.log(error) }) }) }) </script> urls.py path("detail/<int:book_pk>", views.detail, name="detail"), path("detail/<int:book_pk>/like/<int:review_pk>", views.like, name="like"), ..... views.py def detail(request, book_pk): reviews = Review.objects.order_by("-pk") book = Book.objects.get(pk=book_pk) context = { "reviews": reviews, "book": book, } return render(request, "review/detail.html", context) def like(request, book_pk, review_pk): review = Review.objects.get(pk=review_pk) book = Book.objects.get(pk=book_pk) if review.like_users.filter(pk=request.user.pk).exists(): review.like_users.remove(request.user) is_liked = False else: review.like_users.add(request.user) is_liked = True data = { "isLiked": is_liked, } return JsonResponse(data) I got a 404 not found error while writing code for a "like" async function. data-book-id="{{ book.pk }}" data-review-id="{{ review.pk }} … -
django annotate based on another annotate create a duplicate query
I want to calculate number of group members (no_members), sum of the points of the group members(point) and average point per person(avg_point) for each group with annotation: groups = StudyGroup.objects.filter(group_filter).select_related('parent').annotate( no_members=Count('student', distinct=True), point=Sum('student__point__point', filter=point_filter), avg_point=ExpressionWrapper(F('point') / F('no_members'), output_field=FloatField())) but when I check query (groups.query) in avg_point instead of use point/no_members query is SUM(study_league_point.point) / COUNT(DISTINCT users_student.user_id) (point and no_members calculate again). query is: SELECT `study_league_studygroup`.`id`, `study_league_studygroup`.`name`, `study_league_studygroup`.`parent_id`, COUNT(DISTINCT `users_student`.`user_id`) AS `no_members`, SUM(`study_league_point`.`point`) AS `point`, ( SUM(`study_league_point`.`point`) / COUNT(DISTINCT `users_student`.`user_id`) ) AS `avg_point`, `layers_layer`.`id`, `layers_layer`.`name`, `layers_layer`.`type_id`, `layers_layer`.`parent_id`, `layers_layer`.`created`, `layers_layer`.`default`, `layers_layer`.`lft`, `layers_layer`.`rght`, `layers_layer`.`tree_id`, `layers_layer`.`level` FROM `study_league_studygroup` LEFT OUTER JOIN `users_student` ON ( `study_league_studygroup`.`id` = `users_student`.`study_group_id` ) LEFT OUTER JOIN `study_league_point` ON ( `users_student`.`user_id` = `study_league_point`.`student_id` ) INNER JOIN `layers_layer` ON ( `study_league_studygroup`.`parent_id` = `layers_layer`.`id` ) GROUP BY `study_league_studygroup`.`id` but I want use (point / no_members) AS avg_point instead of (SUM(study_league_point.point) / COUNT(DISTINCT users_student.user_id)) AS avg_point -
What are Pharaoh, Grandmother, and Monarchy deletion patterns?
I was looking at the docs for Django CTE Trees and saw the text: Multiple delete semantics: supports Pharaoh, Grandmother, and Monarchy deletion patterns. This meant nothing to me, so I did a bit of googling - and found nothing! Does anyone know what "Pharaoh, Grandmother, and Monarchy deletion patterns" are?