Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Model inheritance: benefits of explicit OneToOneField vs implicit multi-table inheritance OneToOneField
I read here that multi-table inheritance can cause performance issues, and instead explicit OneToOneField is recommended. Here is my situation: class Product(models.Model): title = models.CharField(max_length=200) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=10) category = models.ForeignKey('Category', on_delete=models.CASCADE, blank=False) class Book(Product): publisher = models.CharField(max_length=50) author = models.CharField(max_length=50) isbn = models.CharField(max_length=50) class Shoes(Product): size = models.PositiveSmallIntegerField() colour = models.CharField(max_length=20, choices=[('black', 'Black'), ('white', 'White')]) I don't understand why would explicit OneToOneField bring performance gains, when multi-table inheritance is implemented in exactly the same way: place_ptr = models.OneToOneField( Place, on_delete=models.CASCADE, parent_link=True, ) If this is true despite everything, I would like to know how could I alter my models so they use explicit OneToOneField. So, if I create a Book instance, Product.objects.all() should retrieve that instance of Book, too. -
Django - How to link the current authenticated user with the data provided by a form
Sorry if the question is too basic but I've read the documentation and many articles and none of them seem to answer my question. I want to link a posted form by an user with that user into the DB, so I can query the data provided for each particular user and use delete on CASCADE in the event the user is deleted. I tried creating a Model, then a ModelForm based on that Model. I add a field named "user" in the Model as a ForeignKey, so in the ModelForm is translated to ModelChoiceField which by the way is hidden, since the user shouldn't change that value. But when I try to update the user field in the views.py, nothing happens, the form is saved into the database, but the user field remains as None or Null in the DB. models.py class Foo(models.Model): user = models.ForeignKey(User, related_name='+', on_delete=models.CASCADE) forms.py class FooForm(ModelForm): class Meta: model = Foo fields = ['user', 'field1', 'field2'] exclude = ['user'] views.py def index(request): if request.user.is_authenticated: if request.method == 'POST': foo = FooForm(request.POST) if foo.is_valid(): foo.save(commit=False) foo.user = request.user foo.save() I got the posted Form saved into the DB but the user field is NULL. Of … -
Django: is this data migration going to blow the server memory?
I'm trying to migrate the data from an old table to a new table and I'm not sure what the best way would be. There's the simple solution of creating every object: def migrate_data(apps, schema_editor): UserPreferences = apps.get_model("authentication", "UserPreferences") UserPreferencesOld = apps.get_model("authentication", "UserPreferencesOld") for user_preferences_old in UserPreferencesOld.objects.all(): user_preferences = UserPreferences( date_modified=user_preferences_old.date_modified, email_notifications=user_preferences_old.email_notifications, show_message_deadline_summary=( user_preferences_old.show_message_deadline_summary ), user=user_preferences_old.user, ) user_preferences.save() And the bulk create solution: def migrate_data(apps, schema_editor): UserPreferences = apps.get_model("authentication", "UserPreferences") UserPreferencesOld = apps.get_model("authentication", "UserPreferencesOld") UserPreferences.objects.bulk_create( [ UserPreferences( date_modified=user_preferences_old.date_modified, email_notifications=user_preferences_old.email_notifications, show_message_deadline_summary=( user_preferences_old.show_message_deadline_summary ), user=user_preferences_old.user, ) for user_preferences_old in UserPreferencesOld.objects.all() ] ) The table I need to migrate has tens of thousands of entries and I'm afraid that the first option will take forever, making tens of thousands of requests to the database, while the second option will blow the memory on the server. Any suggestions on what would be the better option? Thanks! -
How do you get the current cursor with CursorPagination?
By default, CursorPagination gives you the next and previous cursors. Is there a way to get the current cursor? -
How can you customize object creation in django?
In django rest framework, it's possible to make a function to customize the process of creating an object inside the serializer of that respective model, but I can't figure out how to do that in "vanilla" django, so to speak. What I need to do is take one field and do a bunch of stuff with it. encode it into a 256 character hash is all I have to worry about now. How can I go about doing what I need? I've been basing myself off of an online course and Django's documentation, but I either couldn't interpret it well enough or I just straight up haven't found it there. Here is the code I have so far, at least what I judge is relevant to the question. It's all in models.py: class SpedFile(models.Model): json_file = models.FileField(max_length=100) sped_file = models.FileField(max_length=100) integrity_hash = models.CharField(max_length=256) line_counter = models.CharField(max_length=150000) created_at = models.DateField(auto_now_add=True) @classmethod def create(cls, json_file): file_bearer = json_file m = hashlib.sha256() m.update(file_bearer.encode('utf-8')) integrity_hash = m.hexdigest() new_object = cls(json_file=file_bearer, integrity_hash=integrity_hash) return new_object -
How to write subquery in django
Is it possible to make following sql query in django select * from ( select * from users ) order by id It is just minimal example. I have a long subquery instead of select * from users. But I can't understand how insert it into subquery. -
Django Jinja2 How to get form data on a different view
I am loading my registration form on the base url (localhost:8000/). It's a Jinja2 template and running on top of Django. Let's FrontEnd app is frontend <form class="registration_form" style="display: none" method="POST" action="/"> <div class="form-group"> <input type="text" class="form-control" id="InputFirst" placeholder="First Name"> </div> <div class="form-group"> <input type="text" class="form-control" id="InputLast" placeholder="Last Name"> </div> <div class="form-group"> <input type="email" class="form-control" id="InputEmail" aria-describedby="emailHelp" placeholder="Enter email"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> <div class="form-group"> <input type="password" class="form-control" id="InputPassword" placeholder="Password"> </div> <button type="submit" class="btn btn-primary btn-lg btn-block actions"> Registration</button> </form> Now, I have written my Registration API, on user app and it's accessed via /user/registration/. How can I send the form data on that VIew instead of the front_end view? I am using APIView of DRF for registration API. I have tried to add {{ url_for('user/registration/') }} on actions. It doesn't work For some reason, I can't use any other front-end framework, I have to make do with jinja2. Thanks in Advance. -
celery task in multiple queues not start
i use django with celery and redis to work with asynchronous tasks. I have three task defined which should run in your own queue. My project structure looks like this: django-project |- api |- task.py |- view.py |- django-project |- settings.py |- celery.py |- __init__.py My tasks defined in the task.py in my api app: @shared_task def manually_task(website_id): print("manually_task"); website = Website.objects.get(pk=website_id) x = Proxy(website, "49152") x.startproxy() x = None @periodic_task(run_every=(crontab(hour=19, minute=15)), ignore_result=True) def periodically_task(): websites = Website.objects.all() for website in websites: x = Proxy(website, "49153") x.startproxy() x = None @shared_task def firsttime_task(website_id): website = Website.objects.get(pk=website_id) x = Proxy(website, "49154") x.startproxy() x = None Now here is my init.py __all__ = ('celery_app',) and the celery settings in the settings.py: CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Europe/Berlin' CELERY_DEFAULT_QUEUE = 'red' CELERY_TASK_QUEUES = ( Queue('red', Exchange('red'), routing_key='red'), ) CELERY_ROUTES = { 'api.tasks.manually_task': {'queue': 'red'}, } My celery.py looks like this: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django-project.settings') app = Celery('django-project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() This was my settings. Now i start all the needed stuff (every line in own terminal): redis-server celery -A django-project worker -Q red python3 manage.py runserver 0.0.0.0:8000 All starts without problems. In the … -
Struggling with connection between Django and Postgres within Docker containers
I've been hitting the following error for awhile now and can't seem to fix it... django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? Multiple resources stated it was simply due to the HOST setting within my DATABASES, but the following is what I am working with and still can't get it to work: DATABASES = { 'default': { 'HOST': 'db', 'ENGINE': 'django_postgrespool2', 'NAME': os.environ.get('PROJECT_HEARSAY_DB_NAME'), 'USER': os.environ.get('PROJECT_HEARSAY_DB_USER'), 'PASSWORD': os.environ.get('PROJECT_HEARSAY_DB_PASSWORD'), 'PORT': os.environ.get('PROJECT_HEARSAY_DB_PORT'), } } Here is the Dockerfile for my Django app: FROM python:3 ENV PYTHONUNBUFFERED 1 COPY . /app WORKDIR /app RUN pip install --upgrade pip RUN pip install -r requirements.txt Here is the Dockerfile for my Postgresql DB: FROM postgres And here is the docker-compose.yml that I am working with: version: "3" services: postgresql: build: context: ./db container_name: db.postgresql ports: - 5432:5432 environment: POSTGRES_DB: "db_name" POSTGRES_USER: "username" POSTGRES_PASSWORD: "password" django: restart: always build: context: ./api command: bash -c "./manage.py migrate && ./manage.py runserver 0.0.0.0:8000" container_name: api.django ports: - 8000:8000 depends_on: - postgresql I'm curious if anyone here could shed some light on what I am doing wrong. Thank you. -
How to create multiple datetimepickers in django template (for loop) and jquery
I am having trouble getting django to display multiple datetimepickers in tabs on a html page. I can get them to work if I specify each element in the jquery outside of a loop, but when I put it in a loop, they don't show (only shows an empty input text box). As this has to be done on an array of varying sizes (min length of 1 and no max), I can't hard code each individual datetimepicker. The for loop on the django template html page works, and each tab and the sections where the datetimepickers go is made, but the jquery won't work. I have tried to make the 4 datetimepickers via a loop (4 per tab, can have 1+ tabs), and they don't create the datetimepicker object. Just creates a input text box. I have also tried putting them all into a class=datetimepicker, which does work, but then I can't add in default data from the array to fill in each datetimepicker, as the only function in jquery is a single one calling the class .datetimepicker. Tried $('#date1').datetimepicker({ defaultDate: array[counter][0] }) in an array to fill in each tab for the date1 datetimepicker, and that does not … -
MySql errors while executing queries on a Django project on AWS Lambda function
I have a Django project hosted on AWS Lambda function. This microservice uses pymysql to connect to AWS Aurora RDS database. This service executes one and only one query over and over again. 1 in 200 times the query fails with EOF packet error. In order to investigate this issue i have implemented a "repeater" which would repeat the same query if one fails (maximum 2 repeats with 0.25 seconds delay). Once again, in a rare ocasion, a query has failed and I expected to see a successful query after the first reattempt. However it failed in all 3 consecutive calls with all DIFFERENT error messages. Error messages (in order): AssertionError: Protocol error, expecting EOF django.db.utils.InternalError: Packet sequence number wrong - got 24 expected 1 django.db.utils.InterfaceError: (0, '') These are errors from 3 separate queries executed against MySql Aurora RDS database. (I just wanted to ephesize that indeed it is not a stack trace but rather different query errors). More useful info: The microservice uses Django ORM to create queries. The database is in Master-Slave configuration and those queries go against a Slave database. The parameters observed in Master and Slave databases (such as CPU usage, free RAM space, various … -
Submit a form, force download a pdf, after that redirect to another page, can we do this without using frontend/js?
I have a post form, I want to download a pdf receipt after submitting form, and then redirect to another page. form.submit >> force downlaod pdf >>> redirect. and I want to do this only at the server-side, is there any idea to do this without using js. -
Serialize related object before primary key is created
So I have a serializer which I have added a custom create method for, because I am using it to insert objects for a many-to-many relationship and am using nested serializers for this. As it stands, when I try to create and object using the DocumentSerializer, I get a "document":["This field is required."] error, because when the documentdomain_set variable is declared, the associated document has yet to be created, and therefore there is no id to be used in the relation. I obviously know how to capture this document_id after saving the new document object, but I am not sure what the best practice is to handle the variable initiation as it stands. Thanks! class DocumentDomainSerializer(serializers.ModelSerializer): domain = serializers.SerializerMethodField('get_domain_id') class Meta: model = DocumentDomain fields = ('document_id', 'domain_id') class DocumentSerializer(serializers.ModelSerializer): documentdomain_set = DocumentDomainSerializer(many=True, required=False) class Meta: model = Document fields = ( 'documentdomain_set', 'id', 'text', 'uploaded_at') extra_kwargs = { 'id': {'read_only': True}, 'uploaded_at': {'read_only': True} } def create(self, validated_data): documentdomain_set = documentdomain_set.pop('documentdomain_set', []) # create document first document = Document.objects.create(**validated_data) # serialize associated domains for documentdomain in documentdomain_set: # get ID of newly-created document, use for relation documentdomain['document_id'] = document DocumentDomain.objects.create(**documentdomain) return document -
Getting "Bad Request" on the post request to Django Rest-Api using serializers
I am trying to save data into a model using django-rest framework. I have already written the api, it works fine when i access it directly using the url to api. But I get a bad-request error when i try to post data using ajax. If it is working fine when data is inserted using the api interface, it should work fine when data is inserted using ajax....but instead i am getting a bad request. here is the AJAX request method(Jquery): $("form").submit(function(event){ event.preventDefault(); var this_ = $(this); var formData =this_.serialize(); $.ajax({ url: "/api/forum/posts/{{ post_question.thread_id.id }}/create", data: formData, method: "POST", success: function (data) { console.log("successfully returned"); console.log(data); displayPosts(); }, }) Serializers are as follow, in api/serializers.py : class ThreadModelSerializer(serializers.ModelSerializer): created_by = UserDisplaySerializer(read_only=True) class Meta: model = Thread fields = '__all__' class PostModelSerializer(serializers.ModelSerializer): posted_by = UserDisplaySerializer(read_only=True) class Meta: model = Post fields = '__all__' Models for the Post and Thread are as follow in models.py: class Thread(models.Model): thread_subject = models.CharField(max_length=250) posted_on = models.DateTimeField(auto_now=True) category = models.CharField(max_length=250) forum_id = models.ForeignKey(Forum, on_delete=models.CASCADE) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Post(models.Model): post_message = models.TextField() thread_id = models.ForeignKey(Thread, on_delete=models.CASCADE) parent_id = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) posted_on = models.DateTimeField(auto_now=True) posted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) and finally the API view is … -
Python django TypeError at /cart/update/ 'NoneType' object is not iterable
enter image description here Hello I have the following error on my browser: TypeError at /cart/update/ 'NoneType' object is not iterable Exception Location: C:\Users\Gijs Machielsen\dev\ecommerce\src\carts\views.py in cart_update, line 19 ########## my views.py contains the following code: from django.shortcuts import render, redirect from products.models import Product from .models import Cart def cart_home(request): cart_obj, new_obj = Cart.objects.new_or_get(request) return render(request, "carts/home.html", {"cart": cart_obj}) def cart_update(request): product_id = request.POST.get('product_id') if product_id is not None: try: product_obj = Product.objects.get(id=product_id) except Product.DoesNotExist: print("Show message, product is gone ") return redirect("cart:home") cart_obj, new_obj = Cart.objects.new_or_get(request) !!!! line 19 if product_obj in cart_obj.products.all(): cart_obj.products.remove(product_obj) else: cart_obj.products.add(product_obj) return redirect("cart:home") ## models.py is the following: from decimal import Decimal from django.conf import settings from django.db import models from django.db.models.signals import pre_save, post_save, m2m_changed from products.models import Product User = settings.AUTH_USER_MODEL class CartManager(models.Manager): def new_or_get(self, request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1: new_obj = False cart_obj = qs.first() if request.user.is_authenticated() and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = Cart.objects.new(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj def new(self, user=None): user_obj = None if user is not None: if user.is_authenticated(): user_obj = user return self.model.objects.create(user=user_obj) Create your models here. class Cart(models.Model): user … -
Page not found after trying to add a new path to the urlpatterns of main urls.py file? (Mosh Python Tutorial)
I'm following Mosh's tutorial video on Python. He begins the django section (https://youtu.be/_uQrJ0TkZlc?t=18085) by installing django 2.1. I am able to open a development server the first time as he does: pip install django==2.1 django-admin startproject pyshop . python manage.py runserver #server works Here are the steps he goes through to add a "products" app/path: python manage.py startapp products Opens views.py from this new products folder and modifies code to this: from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse('Hello World') Creates urls.py inside the products app/folder and adds this code: from django.urls import path from . import views urlpatterns = [ path(' ', views.index) ] Opens the main urls.py in the pyshop folder and adds/modifies the end of the file like this: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('products/', include('products.urls')) ] Mosh goes back to the server and adds /python to the url to get a page with "Hello World" (https://youtu.be/_uQrJ0TkZlc?t=19220) Upon trying to run the server again, I get Page not found error. Is there something I'm missing? I didn't figure it'd be a version issue since I made sure and installed the same 2.1 version. -
Adding a profile to user in django
Following this : https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#onetoone I am having some trouble with this call: @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) In their example I am guessing this works as is on the signup of a new account because the Profile in their example has all fields that can be blank and null. In my case my profile I am trying to maintain here is called: class APOUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) institution = models.ForeignKey("mainpage.InstitutionMember", on_delete=models.PROTECT) gender = models.ForeignKey("mainpage.GenderTable", on_delete=models.PROTECT) on_site_status = models.ForeignKey("mainpage.SiteStatus", on_delete=models.PROTECT) refer_to_as = models.TextField(max_length = 30, blank=True) #if the above is custom room_preference = models.ForeignKey("housing.Room", on_delete=models.PROTECT) Which has references to ultimately what will be drop downs to select form a form (populated by another table with defaults). So do I remove the @reciever and then just have the users fill out the profile separately somehow after they signup and confirm their account? I tried to mix my signup form with the profile form... but kept getting an anonmyous user object had no attribute object apouser in the views.py when I try to mix the signup forms and profile forms: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) profile_form = ProfileForm(request.POST, instance=request.user.apouser) if form.is_valid() and profile_form.is_valid(): … -
convert page to pdf and render on screen
I can convert a page to pdf perfectly, however, I need to render a graphic that is made with javascript, in this case I first need to render the page to be able to compile to pdf and render on screen, could someone help me? I am using lib django-weasyprint -
How to change default image in Django
I have a django app that allows users to fill out a form, and attach an image if they like. If they decide not to attach an image, I want a default image in it's place. The problem is that when the user tries to attach an image during the post creation, it doesn't save. It only saves when the post is edited. model field: image = models.ImageField(upload_to='images/', default = 'noImageAttached.png') This works as expected when a user creates a new post and does not add a new image. The default image 'noImageAttached.png' is used. However, when someone wants to attach an image in theCreateView it will not throw any errors, it just will simply not save the image. When this same post is edited with UpdateView, you can upload an image, and it works. Something in my CreateView is causing it to not work? Or maybe there is a different way of using default in models.py? views.py class assetCreateView(LoginRequiredMixin,CreateView): model = Assets form_class = Asset_Creation_Form template_name = 'addAsset.html' login_url = 'login' success_url = reverse_lazy('home') #these fields are hidden from user, and filled out automatically def form_valid(self, form): form.instance.createdBy = (self.request.user.first_name)+ " "+ (self.request.user.last_name) return super().form_valid(form) -
Postback, filters and sorting data in an App using Django and AJAX
I keep having this problem where I can't order some tables by date. I'm reading this code, I didn't write it so it will be useful if anyone can give me some tips. If I miss some information, just ask me, please. The ListView code: cursor = connections['default'].cursor() start = request.GET['start'] length = int(request.GET['length']) page = int(request.GET['draw']) poll = Poll.objects.get(id=poll_id) if not can_access_poll(request, poll): return JsonResponse({"error": "An error occurred"}) date_from = None period = None date_condition_shown = '' if request.GET.get("period"): period = request.GET['period'] if period and period != 'Total': date_condition, date_condition_shown, date_previous_condition, days_difference, date_from, date_to, filtering_by_date, date_from_previous, date_to_previous, date_from_string, date_from_previous_string = build_dates( period, None) if 'venue_id' in request.GET and request.GET['venue_id'] != '0' and request.GET['venue_id'] != 'undefined': filter_venue_id = request.GET['venue_id'] elif venue_id: filter_venue_id = venue_id else: filter_venue_id = None try: total = PollUser.objects.filter(poll=poll, completed=True).count() query = 'Select v.shown_on, v.source, u.first_name, u.last_name, p.id, v.id, ve.name ' \ 'From app_polluser v ' \ 'Inner join app_customuser u on u.id = v.user_id ' \ 'Inner join app_userprofile p on p.user_id = u.id ' query += 'Left join app_session s on v.session_id = s.id ' query += 'Left join app_router r on s.router_id = r.id ' query += 'Left join app_venue ve on r.venue_id = … -
How to access get request data in django rest framework
How to access GET request data in django rest framework. In the docs, they have mentioned "For clarity inside your code, we recommend using request.query_params instead of the Django's standard request.GET" https://www.django-rest-framework.org/api-guide/requests/ But when I use request.query_params.get('some_vaue') it gives me none even though I pass the data in the request body. sample code example: class TestView(APIView): def get(self, request): test = request.query_params.get('test') print('data',test) ... ... ... When I pass some value in the body of the request in postman and print the value, it actually prints None. -
Django gives 404 Error from previous project
When I'm trying to start new Django project and to run server I have "SOURCE /lo-fi-radio HTTP/1.0" 404 1987 But it's fully new empty project with its own virtualenv. lo-fi-radio is the root directory of my previous project. There are another strange errors too. Full log: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. October 02, 2019 - 17:32:41 Django version 2.2.6, using settings 'company_db_manager.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Not Found: /lo-fi-radio [02/Oct/2019 17:32:45] "SOURCE /lo-fi-radio HTTP/1.0" 404 1987 Traceback (most recent call last): File "/usr/lib/python3.6/wsgiref/handlers.py", line 138, in run self.finish_response() File "/usr/lib/python3.6/wsgiref/handlers.py", line 180, in finish_response self.write(data) File "/usr/lib/python3.6/wsgiref/handlers.py", line 274, in write self.send_headers() File "/usr/lib/python3.6/wsgiref/handlers.py", line 333, in send_headers self._write(bytes(self.headers)) File "/usr/lib/python3.6/wsgiref/handlers.py", line 453, in _write result = self.stdout.write(data) File "/usr/lib/python3.6/socketserver.py", line 803, in write self._sock.sendall(b) ConnectionResetError: [Errno 104] Connection reset by peer [02/Oct/2019 17:32:45] "SOURCE /lo-fi-radio HTTP/1.0" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 36856) Traceback (most recent call last): … -
How to add Q search filter in subquery
How to add a Q search filter on this view subquery. def inventary(request): credits = Credit.objects.filter(account=OuterRef('pk')).values('account_id').annotate(sum_credits=Sum('amount')) debits = Debit.objects.filter(account=OuterRef('pk')).values('account_id').annotate(sum_debits=Sum('amount')) dif =Account.objects.annotate(credit_sum=Subquery(credits.values('sum_credits')),debit_sum=Subquery(debits.values('sum_debits')),balance=F('credit_sum') F('debit_sum')).values_list('name', 'balance') context = { 'credits ': credits , 'debits ': debits , 'dif': dif, } return render(request, 'inventary/inventary.html', context) -
How can I filter out objects where todays date falls within a range of a calculated date?
Here is the code I currently have. models = Model.objects.annotate( start_range=ExpressionWrapper( F('the_date') + datetime.timedelta(days=-7), output_field=DateField(), ), end_range=ExpressionWrapper( F('the_date') + datetime.timedelta(days=-2), output_field=DateField(), ) ).filter( F('today')__range=[F('start_range'), F('end_range')] ) Obviously I can not do a range on F('now') because it's not a database column / keyword but I'm just showing that I have a variable called today that I'm trying to compare against. I feel like I'm close but could use some help wrapping this up. Note: -7 and -2 will be dynamic days but just hardcoded for example. -
In django mapping how to get complete count of choice filed
I want the Count of My (Booking Type) I have 3 Types of choices (choice field in Model) Individual, Group, and Certificate. d1 = Booking.objects.values('booking_type').annotate(booking_count=Count('booking_type')) {f.get('booking_type'): f.get('booking_count') for f in d1} Here below is the Output of Above: But why the code Will Cant give me the Count of Certificate {'GROUP': 2, 'INDIVIDUAL': 3} I Changed Values To filter also But Nothing Works