Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to mock an mutation argument in Django?
I have a mutation that has a decorator that checks the permissions (scopes) from the user token before s/he goes inside it. The decorator gets the input parameter from the mutate method and extracts the token and verify if the user has one of the allowed scopes. The unit tests don't succeed if I don't remove or mock the requires_scope part from the code. The problem is that I don't know exactly what I have to mock to succeed in the unit tests. Should I mock the input itself? The token? The return of the requires_scopes decorator? mutations.py class MyMutation(graphene.Mutation): success = graphene.Boolean() class Arguments: input = graphene.Argument(IdInput, required=True) @classmethod @requires_scopes(['app:first_test_permission', 'app:second_test_permission']) def mutate(cls, root, info, input): pass decorators.py def get_access_token_from_header(request): """ Obtains the Access Token from the Authorization Header """ header = request.context.META.get('HTTP_AUTHORIZATION', None) header = header.split() token = header[1] return token def requires_scopes(scopes: list): """ Determines if the required scope is present in the Access Token Args: scopes (list): The scopes required to access the resource """ def require_scopes(f): @wraps(f) def decorated(*args, **kwargs): token = get_access_token_from_header(args[2]) decoded = jwt.decode(token, verify=False) if decoded.get("scope"): token_scopes = set(decoded["scope"].split()) required_scopes = set(scopes) if required_scopes.intersection(token_scopes): return f(*args, **kwargs) raise Exception({'message': 'You don\'t have … -
Django Subquery in SQL FROM part
The Django Documentation shows how to create a subquery in the SELECT part of the SQL query, but how to create a subquery in the FROM part? i.e: SELECT ... FROM ( SELECT ... FROM ... WHERE ... GROUP BY ... ) WHERE ... ORDER BY ... Here is a specific example in case this helps, but if you can answer the general question above without this example, please do. If we have the models: class MyModel(models.Model): field1 = models.CharField() other_model = models.ForeignKey(OtherModel) class OtherModel(models.Model): field2 = models.CharField() field3 = models.CharField() active = models.BooleanField() Let's say I want to count for each my_model.field1 value the number of OtherModel.field3 values where there are some instances my_model, other_model with my_model.other_model == other_model and other_model.active == True So I would like to have a subquery where I group by field1 and field3 and count the actives: sub_query = MyModels.values('field1', 'othermodel__field3').annotate(actives=Count(Case(When(othermodel__active=True, then=1)))) And then a main query where I group the results of the first query by field1 and count them per group: main_query = qub_query.values('field1').annotate(active_combinations=Count('field1', filter=Q(actives__gt=0))) But this is interpreted in a different way and does not work like this. -
timestamp field needs default value
Here is the code for my models.py: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Mail(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='emails') sender = models.ForeignKey(User, on_delete=models.PROTECT, related_name='sent') recipients = models.ManyToManyField(User, related_name='received') subject = models.CharField(max_length=255, blank=True) body = models.TextField(blank=True) timestamp = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) archive = models.BooleanField(default=False) def serialize(self): ... When I run the python manage.py makemigrations, I get this error: You are trying to add a non-nullable field 'sender' to mail without a default; we can't do that (the database needs something to populate existing rows). But I don't want the sender field to be null and I cannot set a default. For testing, I added null=True to the sender field and I get an error for timestamp: You are trying to add the field 'timestamp' with 'auto_now_add=True' to mail without a default; the database needs something to populate existing rows. To get rid of this error, I added a default=time.time() to the timestamp field. I get this error: The options auto_now, auto_now_add, and default are mutually exclusive. Only one of these options may be present. What is happening? How do I solve these issues? -
Is it possible to filter "Related field" in Django Template?
I am developing an Instagram clone using Django. I wanted to show the latest two comments for each post. As of now, I am only able to show all comments using the below code home.html {% for comment in post.comments.all %} <p>{{ comment.user.username }}: {{ comment.description }}</p> {% endfor %} My models class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post_linked = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') description = models.CharField(max_length=500) comment_posted_on = models.DateTimeField(default=timezone.now) def __str__(self): return "Comment by {} on {}".format(self.user.username, self.post_linked.caption) Is there any way I cal display only the Latest two comment for each post? -
Django does not up - docker compose
I'm trying to up a docker-compose with Django and Mysql, but Django does not up. I saw many people asking the same question, and some answers about it, but none works. docker-compose logs show: web_1 | Traceback (most recent call last): web_1 | File "manage.py", line 22, in <module> web_1 | main() web_1 | File "manage.py", line 18, in main web_1 | execute_from_command_line(sys.argv) web_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line web_1 | utility.execute() web_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 345, in execute web_1 | settings.INSTALLED_APPS web_1 | File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in __getattr__ web_1 | self._setup(name) web_1 | File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 70, in _setup web_1 | self._wrapped = Settings(settings_module) web_1 | File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 177, in __init__ web_1 | mod = importlib.import_module(self.SETTINGS_MODULE) web_1 | File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module web_1 | return _bootstrap._gcd_import(name[level:], package, level) web_1 | File "<frozen importlib._bootstrap>", line 1014, in _gcd_import web_1 | File "<frozen importlib._bootstrap>", line 991, in _find_and_load web_1 | File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked web_1 | File "<frozen importlib._bootstrap>", line 671, in _load_unlocked web_1 | File "<frozen importlib._bootstrap_external>", line 779, in exec_module web_1 | File "<frozen importlib._bootstrap_external>", line 916, in get_code web_1 | File "<frozen importlib._bootstrap_external>", line 846, in source_to_code web_1 … -
How to create custom GraphQLView that implements subscriptions?
I did found a similar post here but that doesn't work. Background I have a list of items that I show on the frontend. Each time these items are updated on the backend. The frontend should get updated too. To make it work I am sending GraphQL subscription query from frontend using fetch API to django backend view where I wanna execute it and send the result back when subscription is completed to update the frontend. Problem When I update the model on the backend the subscriptions doesn't seem to trigger. However as I debugged I can see the events being triggered (post_save) but the subscription doesn't seem to be resolved. Frontend: fetch('http://localhost:8000/custom_graphql', { method: 'POST', headers: { "Content-Type": "application/json", "X-CSRFToken": csrftoken }, body: JSON.stringify({ query: "\ subscription {\ vendorUpdated {\ id\ name\ }\ }\ " }) }) .then(res => res.json()) .then(data => { console.log(data); }) Since graphene-django doesn't support subscriptions I am using graphene-subscription along with it. Backend: urls.py urlpatterns = [ ... path('custom_graphql', views.CustomGraphQLView.as_view(), name='custom_graphql'), ] views.py def clean_query(query): return query.replace("\n","") def get_graphql_result_from(request): body_data = json.loads(request.body.decode("utf-8")) query = clean_query(body_data['query']) result = schema.execute(query, context_value=request) result = result.data return result class CustomGraphQLView(GraphQLCustomCoreBackend, View): def __init__(self, executor=None): super(GraphQLCustomCoreBackend, self).__init__(executor) self.execute_params['allow_subscriptions'] = … -
Django the Note instance doesn't keep the images when form is submitting?
implementing below code, I achieved this 1 Note model with many Images. the uploading_views is working fine. Multiple Uploads at the same time, with same Choose File button, & all save together. Now i want to perform the PostUpdateViews for updating the Note. i also get the note data into the form instead images. The code of PostUpdateViews function is only update note instance [title, text] instead images. when i submit the form the form is create new images it's not changing the old images. how can i get Note related images into the Note form and update it. I would be grateful for any help. Models class Note(models.Model): title = models.CharField(max_length=30) text = models.TextField(null=True, blank=True) class Images(models.Model): note = models.ForeignKey(Note, on_delete=models.CASCADE) image = models.ImageField(upload_to='files/', null=True, blank=True) Views def uploading_views(request): if request.method == "POST": form = NoteFullForm(request.POST or None, request.FILES or None) if form.is_valid(): title = form.cleaned_data['title'] text = form.cleaned_data['text'] note_obj = Note.objects.create(title=title, text=text) # create will create as well as save too in db. for f in request.FILES.getlist('images'): Images.objects.create(note=note_obj, image=f) return HttpResponse('success') else: form = NoteFullForm() return render(request, 'uploading.html', {'form': form}) def PostUpdateViews(request, id): note = Note.objects.get(id=id) form = NoteFullForm(request.POST or None, request.FILES or None, instance=note) if form.is_valid(): title … -
NameError: name 'SET_NULL' is not defined [closed]
So I want to set on_delete=SET_NULL but it gives me an error "NameError: name 'SET_NULL' is not defined", documentations say this should work but it's not. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Book(models.Model): name = models.CharField(max_length=200) description = models.TextField() image = models.ImageField() price = models.IntegerField() class Category(models.Model): name = models.CharField(max_length=100) book = models.ForeignKey(Book, on_delete=SET_NULL, null=True) class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' class Order(models.Model): order_id = models.CharField(max_length=500) user = models.ForeignKey(User, on_delete=SET_NULL, null=True) book = models.ForeignKey(Book, on_delete=SET_NULL, null=True) -
Apache mod_wsgi not using venv file for django
I'm trying to run my django project with apach2, here is my /etc/apache2/sites-availabe/myproject.conf file VirtualHost *:80> . . . Alias /static /myproject/static <Directory /myproject/static> Require all granted </Directory> <Directory /myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-home=/myproject/venv python-path=/myproject WSGIProcessGroup myproject WSGIScriptAlias / /myproject/myproject/wsgi.py I have two versions of python on my machine, v3.6 and v3.9. I used python 3.9 for my venv but when I run the project I get the following error in the apache2 error.log file 16:22:51.522214 2021] [wsgi:error] [pid 17379] [remote 156.215.213.11:38592] mod_wsgi (pid=17379): Target WSGI script '/myproject/src/myproject/wsgi.py' cannot be loaded as Python mod$[Tue Jan 26 16:22:51.522294 2021] [wsgi:error] [pid 17379] [remote 156.215.213.11:38592] mod_wsgi (pid=17379): Exception occurred processing WSGI script '/myproject/src/myproject/wsgi.py'. [Tue Jan 26 16:22:51.522533 2021] [wsgi:error] [pid 17379] [remote 156.215.213.11:38592] Traceback (most recent call last): [Tue Jan 26 16:22:51.522566 2021] [wsgi:error] [pid 17379] [remote 156.215.213.11:38592] File "/myproject/src/myproject/wsgi.py", line 12, in [Tue Jan 26 16:22:51.522585 2021] [wsgi:error] [pid 17379] [remote 156.215.213.11:38592] from django.core.wsgi import get_wsgi_application [Tue Jan 26 16:22:51.522606 2021] [wsgi:error] [pid 17379] [remote 156.215.213.11:38592] ModuleNotFoundError: No module named 'django' [Tue Jan 26 16:22:51.857115 2021] [wsgi:error] [pid 17379] [remote 156.215.129.117:38596] mod_wsgi (pid=17379): Target WSGI script '/myproject/src/myproject/wsgi.py' cannot be loaded as Python mo$[Tue Jan 26 … -
Django- create_user() function not saving data to database
I have custom User model. I tried to create new user using create_user(), by calling it from view, but data is not getting saved to database. models.py class UserManager(BaseUserManager): def create_user(self, email, username, password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = self.model(username=username, email=self.normalize_email(email)) user.set_password(password) user.save(using=self._db) return user views.py user = { 'username': generate_username(name), 'email': email, 'password': password} user = User.objects.create_user(**user) user.is_verified = True user.save() -
Couldn't Install django-rest-framwork
I am getting these two errors while installing Django_rest_framwork using pip. ERROR: Could not find a version that satisfies the requirement djangorestframwork ERROR: No matching distribution found for djangorestframwork although i have following versions of all requirments: python = 3.9.1 django = 3.1.5 pip = 21.0 screenshot -
django's form is not saved in store
I have a quiz form and when I want to save the answer the model does not store its question. I want to validate the form and save it when if form.is_valid (): I remove it and instead of AnswerForm I use the direct Answer model then it saves but not so. How to change it so that I can validate it and save it with the help of the form? my code -> models.py from django.db import models # Create your models here. from django.core.exceptions import ValidationError class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE, related_name="questions") answer=models.CharField(max_length=100,blank=True) def __str__(self): return str(self.questin) forms.py from django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Question,Answer class QuestionForm(forms.ModelForm): class Meta: model=Question fields="__all__" class AnswerForm(forms.ModelForm): class Meta: model=Answer fields="__all__" views.py from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from .forms import QuestionForm,AnswerForm from .models import Question,Answer import random from django.forms import modelformset_factory def home(request): form=QuestionForm if request.method=='POST': form=QuestionForm(request.POST) if form.is_valid(): form.save() return render(request, "question/base.html", {"form":form}) def ans(request): questions=Question.objects.all() form=AnswerForm() if request.method=="POST": if form.is_valid(): qu=request.POST["i_id"] question_id=int(qu) answ=AnswerForm(questin=question_id,answer=request.POST["answer"]) answ.save() return render(request, "question/ans.html", … -
Django - Save Form Value in Different Views
I'm trying to create a small app in which a user can view an event, submit a form indicating the quantity of tickets they would like, view their basket and finally go to a checkout page. My problem is that after I submit a form for event1, the value that is posted is lost when I try to view another event or refresh the basket. How can I prevent this from happening? I need to use Django to make use of a python module during the checkout process so I need to be able to retrieve the quantities submitted for any event in the final checkout view. My views.py file: def basket(request): context = {'Event 1 Tickets': event1_tickets, 'Event 2 Tickets': event2_tickets} return render(request, 'first_app/basket.html', context) def event2(request): form = forms.TicketForm() form = forms.TicketForm(request.POST) if request.POST: if form.is_valid(): # form.save(commit=True) quantity = form.cleaned_data['quantity'] return render(request,'first_app/basket.html',{'event2_tickets': form.cleaned_data}) else: form = TicketForm() return render(request, 'first_app/event2.html', {'form': form}) def event1(request): form = forms.TicketForm() form = forms.TicketForm(request.POST) if request.POST: if form.is_valid(): # form.save(commit=True) quantity = form.cleaned_data['quantity'] return render(request,'first_app/basket.html',{'event1_tickets': form.cleaned_data}) else: form = TicketForm() return render(request, 'first_app/event1.html', {'form': form}) My forms.py: from django import forms class TicketForm(forms.Form): quantity = forms.IntegerField(label="Ticket Quantity",min_value=1,max_value=9,required=True, widget=forms.NumberInput) My event1/event2.html: <!DOCTYPE … -
How can I get self.fields element value in forms file?
In my forms.py file I have method called r_valid and it is used in views.py file. from django.shortcuts import render, redirect from .forms import UserRegisterForm from django.contrib import messages def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.r_valid() form.save() username = form.cleaned_data.get('username') messages.success(request, f'Created Account for {username}!') return redirect('main') else: form = UserRegisterForm() context = { 'form': form, } return render(request, 'register.html', context) The meaning of it is to ad few more barriers for user which is creating an account. The problem is that in browser it returns an error => TypeError at /register/ 'CharField' object is not subscriptable Here you can see that problem is that I can't get self.fields['username']. So please explain how can I get the username value. from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core.exceptions import ValidationError class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] def r_valid(self): j = self.fields['username'] if j[0] in '0123456789': raise ValidationError('The username can\'t start with number') if len(j) < 6: raise ValidationError('That username is too short') for c in j: if c in '@+-/': raise ValidationError('Your username can\'t contain @, +, - or /') … -
Django : Page not found (404)
Whenever I try to log in with username and password this happens: my project name is:corey_schafer app name for user stuff is: users projects urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('register/', include('users.urls')) ] users urls.py : from django.urls import path from . import views urlpatterns = [ path('', views.register, name='register'), path('signup', views.signup, name='signup'), path('login/', views.login, name='login'), path('logout/', views.logout, name='logout'), ] users views.py: [![enter image description here][2]][2] if views.py image not showing please go here:https://i.stack.imgur.com/auZxo.png if any other file is needed to solve this problem please me -
How to keep the data when pushing code changes to heroku [duplicate]
I deployed a django application for the first time using heroku, and of course i had some bugs in my code that needed some changes , so i had to change the code base , push to github repository and finally pushed the project to heroku so i ran these commands in order : git add . git commit -m "message" git push git push heroku main But i lost the data of the database .. So the main question here is how to keep the data after changing to the code base and deploying again .. -
how to set WSGI of appache2 to work with python 3.7?
i am using ubuntu 16.05, i have installed python3.7 and set it to default using this instructions: Unable to set default python version to python3 in ubuntu when i type python in the console i get python3.7 , i tried to set appache2 to work with python3.7 using : sudo apt-get --yes install python3-pip apache2 libapache2-mod-wsgi-py3 sudo a2enmod wsgi sudo apt install --yes python-django-common sudo apt-get install --yes python-django but still i get exceptions of import packages that are already installed in /var/log/apache2/error.log when try to reach out to the server that i don't get at the terminal like this : Traceback (most recent call last): File "/home/ubuntu/mu_code_path/wsgi.py", line 11, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named 'django' mod_wsgi (pid=75005): Target WSGI script '/home/ubuntu/mu_code_path/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=75005): Exception occurred processing WSGI script '/home/ubuntu/mu_code_pathwsgi.py'. Traceback (most recent call last): File "/home/ubuntu/mu_code_path1/wsgi.py", line 11, in <module> from django.core.wsgi import get_wsgi_application and mod_wsgi (pid=75005): Target WSGI script '/home/ubuntu/mu_code_path/ut_pr_01/wsgi.py' cannot be loaded as Python module. even though i have django installed in python 3.7 another error i get is after service restart : mod_wsgi (pid=89300): Call to 'site.addsitedir()' failed for '(null)', stopping. -
Django redirect to login url with next ,without using method decorator
I have multiple links on my page which redirects user to take quiz. Some quiz requires user to login or create an account and some does not. def dispatch(self, request, *args, **kwargs): self.quiz = get_object_or_404(Quiz, url=self.kwargs['quiz_name']) if self.quiz.draft and not request.user.has_perm('quiz.change_quiz'): raise PermissionDenied try: self.logged_in_user = self.request.user.is_authenticated() except TypeError: self.logged_in_user = self.request.user.is_authenticated if self.logged_in_user: self.sitting = Sitting.objects.user_sitting(request.user, self.quiz) else: self.sitting = self.anon_load_sitting() if self.sitting is False: if self.logged_in_user: return render(request, self.single_complete_template_name) else: return redirect(settings.LOGIN_URL) return super(QuizTake, self).dispatch(request, *args, **kwargs) I would like user to redirect like how method decorator does login/?next=/quiz/f506cb92-ccca-49ff-b2e5-730bbfea6a5a/take/ but instead I get /login/ I would like my user to come back to the page instead of going to "/dashboard" In my settings I have LOGIN_REDIRECT_URL ="/dashboard" -
api = get_api(request) NameError: name 'request' is not defined - Celery/Django/Twitter API
I have the following function for my Django app using the Twitter API. It all works well but when trying to make it a background task with Celery I get the following error "api = get_api(request) NameError: name 'request' is not defined" I've tried splitting the function differently. Getting the API within the function itself. I just seem to get different errors with everything I try. Can anyone help? I just would like the authorised user to be able to run the function and carry on browsing whilst it works away. views.py from django.shortcuts import render from .models import * from django.http import * from django.urls import reverse from django.contrib import messages from auto_tweet_liker.utils import * from AutoTweetLiker.settings import DEFAULT_FROM_EMAIL from AutoTweetLiker.celery import liking # from profanityfilter import ProfanityFilter import tweepy import time import os def like(request): liking.delay() return render(request, "home.html") def auth(request): # start the OAuth process, set up a handler with our details oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) # direct the user to the authentication url # if user is logged-in and authorized then transparently goto the callback URL auth_url = oauth.get_authorization_url(True) response = HttpResponseRedirect(auth_url) # store the request token request.session['request_token'] = oauth.request_token return response def callback(request): verifier = … -
coverage.py not reporting error from run command
I have a bash script that runs my tests: #!/bin/bash coverage run --source='directory_for_coverage' manage.py test coverage report --fail-under=87 but when I run the script it only returns an error code if the coverage fails, not if one of the tests fails. I would think that because I am not using the --ignore-errors switch that coverage run should return the error code from the failing test. What am I missing? -
How to setup Celery on Django start in a docker-compose environment?
I have a working Django Docker Project with a celery setup with redis as backend. Actually I have to start my container e.g. docker-compose up and after that I run in a other terminal docker compose exec [containername] celery -A [projektname] worker -l INFO So far everything is fine, but for debugging reasons I don't want to restart celery after every docker restart and I want to integrate the command after the docker containers are successfully started. So how do I start celery after project startup automatically in a docker environment? -
javasvript is not printing to console after click
Hello i'm new in django and js. Problem: I'm trying to pass from html <button> - (line 26) through javascript to my view in django but data parameters are not printed in console the error i get in console the button i'm getting class from is in line 26 in right view js function and html -
Django initialising AppConfig multiple times
I wanted to use the ready() hook in my AppConfig to start django-rq scheduler job. However it does so multiple times, every times I start the server. I imagine that's due to threading however I can't seem to find a suitable workaround. This is my AppConfig: class AnalyticsConfig(AppConfig): name = 'analytics' def ready(self): print("Init scheduler") from analytics.services import save_hits scheduler = django_rq.get_scheduler('analytics') scheduler.schedule(datetime.utcnow(), save_hits, interval=5) Now when I do runserver, Init scheduler is displayed 3 times. I've done some digging and according to this question I started the server with --noreload which didn't help (I still got Init scheduler x3). I also tried putting import os if os.environ.get('RUN_MAIN', None) != 'true': default_app_config = 'analytics.apps.AnalyticsConfig' in my __init__.py however RUN_MAIN appears to be None every time. Afterwards I created a FileLock class, to skip configuration after the first initialization, which looks like this: class FileLock: def __get__(self, instance, owner): return os.access(f"{instance.__class__.__name__}.lock", os.F_OK) def __set__(self, instance, value): if not isinstance(value, bool): raise AttributeError if value: f = open(f"{instance.__class__.__name__}.lock", 'w+') f.close() else: os.remove(f"{instance.__class__.__name__}.lock") def __delete__(self, obj): raise AttributeError class AnalyticsConfig(AppConfig): name = 'analytics' locked = FileLock() def ready(self): from analytics.services import save_hits if not self.locked: print("Init scheduler") scheduler = django_rq.get_scheduler('analytics') scheduler.schedule(datetime.utcnow(), save_hits, interval=5) … -
Django: How to annotate query with Count of distinct occurrences of field combination?
Ideally I would like to use the Count aggregator to count distinct appearances of two fields, instead of just one: q = Tag.objects.annotate(success=Count(['artifact__event__session', 'artifact'], distinct=True)) but this does not seem to be allowed. I came up with the hacky solution of concatenating the fields I want to count the distinct combinations of: q = Tag.objects.annotate(success=Count(Concat('artifact__event__session', 'artifact'), distinct=True)) But this does not seem like the right thing to do. Is there a better way? More background information: The actual query is more like: q = Tag.objects.annotate(success=Count(Concat('artifact__event__session', 'artifact'), filter=Q(artifact__event__success=True, artifact__event__user=user), distinct=True)) which has the meaning: "For each tag, give me the number of distinct session-artifact combinations of artifacts that are tagged with that tag and sessions that included that artifact, where an event that belongs to this user was successful" with the models being: class Artifact(models.Model): tags = models.ManyToManyField(Tag) ... class Event(models.Model): artifact = ForeignKey(Artifact) session = ForeignKey(Session) success = BooleanField() user = ForeignKey(User) ... class Session(models.Model): ... -
Представление поля в админке Django
В модели есть функция def variant(self, *args, **kwargs): queryset = list(Supplier_items.objects.filter(si_ean__contains = self.order_ean).all()) return queryset Работает правильно, но я хочу выводить данные из этого поля в админке как select/options. Помогите куда копать. Спасибо