Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django database function to extract week from date (if week starts on Saturday)
loads_of_dedicated_customers = Load.objects.filter(customer__is_dedicated=True).exclude(load_status='Cancelled').values('customer__name').annotate(year=ExtractYear('drop_date'), week=ExtractWeek('drop_date').annotate( loads_count=Count('id'), sum_revenue = Sum('billable_amount'), sum_miles = Sum('total_miles'), rate_per_mile = ExpressionWrapper(F('sum_revenue') / NullIf(F('sum_miles'), 0), output_field=DecimalField(max_digits=7, decimal_places=2)), ) I have this query that groups by year and week. However, I need the results by week where the week starts on Saturday. Is there a simple way to do this or should I create a week columns in the table and save it there? Thanks! -
Can't edit anything in Django CMS due to cross-origin error
About three months ago, I upgraded our old Django and CMS application to the (then) latest LTS versions (4.2.3 for Django, 3.11.3 for django-cms). After the upgrade, I got the following error when I tried to edit anything from the CMS toolbar or the CMS plugins after a successful login: SecurityError: Blocked a frame with origin "http://localhost:8000" from accessing a cross-origin frame. A short Google search later I was able to fix the issue by setting the CSRF_TRUSTED_ORIGINS in settings.py (depending on the environment). This worked like a charm until a few weeks ago, when suddenly the same error appeared again. This happens on all our environments - including local - despite the fact that nothing new was deployed since the beginning of July '23. First, I tried everything in this guide: https://noumenal.es/notes/til/django/csrf-trusted-origins/ Our staging and production django app is behind a proxy, so I verified that HttpRequest.is_secure() returns True and the X-Forwarded-Proto header is set to https in the production environment. But this happens also on my local machine, where there is no HTTPS. I also verified that the CSRF cookie value and the CSRF token param in requests are, in fact, the same. Then I tried to install … -
How to enable flow.run_local_server() for HTTPs in Django?
My code was working accurate on localhost. But not when I try to host in DigitalOcean Droplet. from __future__ import print_function from googleapiclient.discovery import build from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload from google_auth_oauthlib.flow import InstalledAppFlow from google.oauth2.credentials import Credentials from google.auth.exceptions import RefreshError from google.auth.transport.requests import Request from django.conf import settings from django.shortcuts import redirect import argparse import base64 import io, os import shutil import requests from pebble import concurrent class Drive: SCOPES = ['https://www.googleapis.com/auth/drive'] extensions = {"csv": "text/csv", "mpeg": "video/mpeg"} def __init__(self): self.creds = self.load_credentials() if self.creds is not None: self.service = build('drive', 'v3', credentials=self.creds) else: self.service = None @concurrent.process(timeout=45) def create_process(self): creds = None token_path = 'token.json' if os.path.exists(token_path): creds = Credentials.from_authorized_user_file(token_path, scopes=self.SCOPES) if not creds or not creds.valid: flow = InstalledAppFlow.from_client_secrets_file( settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, self.SCOPES) creds = flow.run_local_server(host="somedomain.com",port=443) with open('token.json', 'w') as token_file: token_file.write(creds.to_json()) # Attempt to refresh the token try: print("refresh") creds.refresh(Request()) except Exception as e: print("Error refreshing token:", str(e)) flow = InstalledAppFlow.from_client_secrets_file( settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, self.SCOPES) creds = flow.run_local_server(host="somedomain.com",port=443) with open('token.json', 'w') as token_file: token_file.write(creds.to_json()) return creds def load_credentials(self): try: process = self.create_process() creds = process.result() # Wait for the process to complete except TimeoutError: creds = None print("Task was canceled due to a timeout.") return creds What I figured … -
Remove duplicate variant in queryset in django
class ProductEntry(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product_entries") price = models.DecimalField(max_digits=8, decimal_places=0) quantity = models.PositiveIntegerField(default=0) image = models.ForeignKey(Image, on_delete=models.PROTECT, related_name="product_entries", blank=True, null=True) variants = models.ManyToManyField(Variant) inventory_management = models.BooleanField(default=True) def get_variants(self): print(self.variants.values()) get_variants return bottom resut: <QuerySet [{'id': 3, 'name': 'Red', 'image_id': None, 'color': '#C80000FF', 'category': 'C'}, {'id': 1, 'name': 'Black', 'image_id': None, 'color': '#1F1F1FFF', 'category': 'C'}]> <QuerySet [{'id': 2, 'name': 'Purple', 'image_id': None, 'color': '#2D1952FF', 'category': 'C'}]> <QuerySet [{'id': 3, 'name': 'Red', 'image_id': None, 'color': '#C80000FF', 'category': 'C'}]> <QuerySet [{'id': 4, 'name': 'Green', 'image_id': None, 'color': '#009812FF', 'category': 'C'}]> As a result, red color has been repeated twice, I want to delete one of them self.variants.values().distinct("name") -
Django project not running after I have updated the python version of the system
I had created a django project a couple of months ago. Now I wanted to do a new project and updated the python version of my system and the privious project is not working. This project was created by using virtualenv. I am new at django and don't understand what is the problem. I thought that virtual environment is supposed to create an isolated environment for a project with all the necessary dependencies. Please help me with this and thank you in advance. It shows this error. enter image description here ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
Scheduled task on Django with Windows Server
I have a Django project that must be run on Windows Server machine. I can't install any additional software such as RabbitMQ or Docker. Only pip modules are available. As far as I know Celery can't work on windows. Is there a way to implement scheduled tasks in my Django project working in such an environment? -
Hand user instance to ModelForm in Admin
I want to access the currently logged in user, show the username, but make it unchangeable: models.py: class Comment(models.Model): desc = models.TextField(max_length=512) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=CASCADE) class Meta: abstract = True class Status(Comment): icon = TextField(blank=True) admin.py: class StatusAdminForm(forms.ModelForm): image_file = forms.ImageField(required=False, label="Icon") def __init__(self, *args, user, **kwargs): self.user = user super().__init__(*args, **kwargs) def clean_image_file(self): cleaned_data = super().clean() ... return cleaned_data def clean(self): cleaned_data = super().clean() cleaned_data["user"] == self.user if "image_file" in self.changed_data: self.instance.icon = self.cleaned_data["image"] return cleaned_data class StatusAdmin(admin.ModelAdmin): list_display = ("get_icon", "created", "updated", "user") def get_form(self, request, *args, **kwargs): form = StatusAdminForm(request.POST, request.FILES, user = request.user) return form def get_icon(self, obj): return format_html("""<img src="{obj.icon}" """>) so what I want is to show the user as readonly field in the StatusAdminForm. But I get the error: form = ModelForm(request.POST, request.FILES, instance=obj) TypeError: 'StatusAdminForm' object is not callable. -
Duplicate entry error in ManyToManyField in Django model
Duplicate entry error in ManyToManyField in django model. We are using unique_together option in Meta class but that not associated with this field. This is my model:- class Staff(models.Model): name = models.CharField(max_length=50) shortname = models.CharField(max_length=50) email = models.CharField(max_length=50) phone = models.CharField(max_length=15) merchant = models.ForeignKey(Merchant, on_delete=models.CASCADE, related_name='merchant_staff') stores = models.ManyToManyField(Location, null=True, blank=True) pin = models.PositiveIntegerField(validators=[MinValueValidator(1000), MaxValueValidator(9999)]) is_active = models.BooleanField(default=True) class Meta: unique_together = (('pin', 'merchant'), ('shortname', 'merchant'),) this is my error:- duplicate key value violates unique constraint "merchants_staff__staff_id_locatio_2fb867d4_uniq" -
Not able to display validation error messages properly
I am using messages class offered by Django to display error message on top of the form with a red background as you can see below, <div class="w3-row w3-container" style="width: auto; margin-left: 5%; margin-top: 2%; margin-right: 5%;"> <div class="w3-half" style="width: 60%;"> <p> Sign Up </p> </div> <div class="w3-half w3-center w3-border w3-round w3-border-black" style="width: 40%;"> <div class="w3-card-4 w3-border w3-border-black w3-pale-blue" > <h4> Registration Form</h4> </div> <form method="post" action=""> {% if messages %} <ul class="messages w3-red"> {% for message in messages %} <li> {{ message }} </li> {% endfor %} </ul> {% endif %} {% csrf_token %} {{form.as_p}} <input type="submit" class="w3-button w3-black w3-round w3-hover-red" value="Register" style="margin-left: 25px;"> </form> <p> Already signed up? Please <a href="{% url 'user_login' %}" > Login </a> </p> </div> </div> In the below views.py I am doing some validations, the problem I am facing is the messages are not getting displayed on top of the form with red background. Instead they are getting displayed above each of the input field with no background color form = MyUserCreationForm() user = User() if request.method == "POST": form = MyUserCreationForm(request.POST) if form.is_valid(): #user = form.save(commit=False) user.first_name = request.POST.get('first_name') user.last_name = request.POST.get('last_name') user.username = request.POST.get('username').lower() user.email = request.POST.get('email').lower() password1 = request.POST.get('password1') password2 … -
403 Forbidden Error when sending POST request in React+Django project
I am trying to make a website and I am in the process of integrating the React frontend into the Django backend. I am trying to send a post request from my frontend into the backend. If I run my frontend and backend separate on ports 3000 and 8000, I dont get an error, my request goes trough. But with them running on the same port (7000), I get the 403 forbidden error. Here is part my frontend: const handleSubmit = async (formData) => { try { const response = await axios.post('http://127.0.0.1:7000/backend/api/create_message/', formData); console.log('Message sent successfully:', response.data); } catch (error) { console.error('Error sending message:', error); } }; Here is my views.py: @api_view(['POST', 'GET']) def create_message(request): if request.method == 'POST': serializer = MessageSerializer(data=request.data) if serializer.is_valid(): serializer.save() # Send mail name = request.POST.get('name') phone = request.POST.get('phone') email = request.POST.get('email') message = request.POST.get('message') subject = "Contact Form" content = f"Name: {name} \n" \ f"Phone: {phone}\n" \ f"Email: {email}\n" \ f"Message: {message}" from_mail = settings.EMAIL_HOST_USER recipient_list = ['email'] send_mail(subject, content, from_mail, recipient_list, fail_silently=False) messages.success(request, "Message successfully sent", extra_tags='success') form = MessageForm() context = {'form': form} template = '../templates/lpadj/message_form.html' return render(request, template, context) messages.warning(request, "Message not sent", extra_tags='warning') form = MessageForm() context = {'form': form} … -
Secure_ssl_redirect not working in django
I am trying to redirect my django application which was running previously in http:// to https:// In settings.py file. I added SECURE_SSL_REDIRECT = True SECURE_PROXY_SSL_HEADER =( 'HTTP_X_FORWARDED_PROTO','https') ``` Still it didn't redirect or show any error.i tried without secure_proxy_ssl_heade, it didn't work -
IIS server django.core.exceptions.ImproperlyConfigured
I am trying to deploy my django project on windows IIS server using wfastcgi. This project contains multiple apps and post completion of all the steps mentioned when i try to open the url it gives me following error. Thanks in Advance!! File "C:\Python38\Lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "C:\Python38\Lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "C:\Python38\Lib\site-packages\wfastcgi.py", line 605, in get_wsgi_handler handler = handler() File "C:\Python38\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "C:\Python38\lib\site-packages\django_init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python38\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Python38\lib\site-packages\django\apps\config.py", line 222, in create return app_config_class(app_name, app_module) File "C:\Python38\lib\site-packages\django\apps\config.py", line 47, in init self.path = self._path_from_module(app_module) File "C:\Python38\lib\site-packages\django\apps\config.py", line 86, in _path_from_module raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: The app module <module 'OnboardingApp' (namespace)> has multiple filesystem locations (['D:\RPA\CoreRPA_Webapp\OnboardingApp', 'D:\RPA\CoreRPA_Webapp\.\OnboardingApp']); you must configure this app with an AppConfig subclass with a 'path' class attribute. -
Creating forms in Django with multiple Many-to-Many fields in Models
I have these three models with two many to many fields in BlogPost models like class Category(models.Model): name = models.CharField(max_length=150) def __str__(self) -> str: return self.name class Tag(models.Model): name = models.CharField(max_length=150) def __str__(self) -> str: return self.name class BlogPost(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User , on_delete=models.CASCADE) categories = models.ManyToManyField(Category) tags = models.ManyToManyField(Tag) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title and form on client side as follow {% extends 'blog_project/base.html' %} {% load widget_tweaks %} {% block content %} <div class='login-container'> <h2 class='login-heading'> Create New Post </h2> <form class='login-form' method='post'> {% csrf_token %} {% for field in form.visible_fields %} <div class="form-group pb-3"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {{ field|add_class:'form-control' }} {% for error in field.errors %} <span class="help-block">{{ error }}</span> {% endfor %} </div> {% endfor %} <div class='form-group'> <button type = 'submit'>Post</button> <a href="{% url 'blog:blog_list' %}">Go Back</a> </div> </form> </div> {% endblock%} it allows me to select from the existing categories but not allows to add other categories. I want to create a form in django that allows a user to select from the categories on client side as well as create new categories or tags and save them to the … -
Problems with booking site. Cannot remove taken hours
I started building my first website with Django. Trying to create website for my girlfriend`s bussines(manicure salon), and have some problems. First problem was booking form, and picking free hours. Managed to find solution with 2 models and OneToOne relation: class FreeHoursModel(models.Model): EARLY = '10:00' MID = '13:00' LATE = '16:00' HOURS = [(x, x) for x in (EARLY, MID, LATE)] time = models.CharField( max_length=20, choices=HOURS, default=1, ) date = models.DateField( ) def __str__(self): return f"{str(self.date)} - {self.time}" class Customer(models.Model): MAX_LENGTH = 25 name = models.CharField( max_length=MAX_LENGTH, ) last_name = models.CharField( max_length=MAX_LENGTH, ) phone_number = models.IntegerField() date_of_booking = models.DateField( auto_now_add=True ) hours = models.OneToOneField( FreeHoursModel, on_delete=models.DO_NOTHING ) class Meta: get_latest_by = 'date_of_booking' Second problem is how to remove taken hours. These are my views: class IndexView(generic.TemplateView): template_name = 'landing_page/landing_page.html' class BookingView(generic.CreateView): template_name = 'booking_page/booking.html' success_url = reverse_lazy('summary') form_class = CustomerForm def form_valid(self, form): name = form.cleaned_data['name'] last_name = form.cleaned_data['last_name'] phone_number = form.cleaned_data['phone_number'] hour = str(form.cleaned_data['hours']) # print(hour.encode("utf-8")) return super(BookingView, self).form_valid(form) def get_success_url(self): if self.success_url: return self.success_url return super().get_success_url() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['customer'] = CustomerForm() return context class SummaryView(generic.TemplateView): template_name = 'booking_page/summary.html' # if Customer.objects.all(): # latest_created_booking = Customer.objects.latest() # latest_taken_hour_id = latest_created_booking.hours_id # latest_taken_hour = FreeHoursModel.objects.filter(id=latest_taken_hour_id)[0] # … -
I am trying to delete a comment with dynamic success url in my Django Project but it gives me a 404
So The code for this view is My Models, Urls and everything is fine and I event went to check for the data I am requesting manually and funny enough it appeared there. Can someone tell me what mistake is there? class CommentDeleteView(OwnerDeleteView): model = Comment template_name = "ads/comment_delete.html" # https://stackoverflow.com/questions/26290415/deleteview-with-a-dynamic-success-url-dependent-on-id def get_success_url(self): ad = self.object.ad ctx={'ad':ad.id} return reverse_lazy('ads:ad_detail', ctx) -
Where are dokku persistent storage files actually stored on a Mac host machine?
Where are dokku persistent storage files actually stored on a host machine? The documentation says the location is /var/lib/dokku/data/storage/ - but that directory doesn't even exist on my macos m2 host machine - not even /var/lib/dokku/ exists. Docker is installed via Docker Desktop. Whilst I can successfully map a container directory to dokku persistent storage location: dokku storage:ensure-directory myapp dokku storage:mount myapp /var/lib/dokku/data/storage/myapp:/code/media dokku ps:restart myapp and writing files to /code/media/ works, and the files are persisted, and /code/media/ is shown to be a mount point to the host's /var/lib/dokku/data/storage/myapp dir in Docker Desktop's view of the container - when I actually look at that host location, it doesn't exist! e.g. ls /var/lib/dokku/data/storage/myapp No such file or directory Despite this, the solution works and files written to the /code/media directory persist between container re-creations, so they must be kept somewhere. I can't see any related volumes. The only clue is that /var/lib/dokku/data/storage/myapp exists inside the myapp container, albeit with no files in it. Note, my dokku app myapp is a Django app deployed via a Dockerfile (since buildpacks don't work on ARM). -
How to list multiple model records ordered by date in one list
I'm working on ordering system, where a client can request different orders (transfer, shipping, contract, etc.) each of these orders are in different models. I want to implement a page for all client requests, this list should be a combination from Transfer, Shipping, Contract models, and I want to order them by date. Since I have records from different models, then I believe using Django ListView is not an option in this case since ListView requires specifying one model and in my scenario I need three models or even more. I would like to know what is the best way of achieving this in a very effective way?. NOTE: I don't want to combine all of these models into one models, as all of them have different requirements and procedures. I'm thinking of creating a TemplateView and call a function in the get_context_data() which calls all the models, chain the, then order them using lambda function. BUT, I think this approach is not recommended when I have a filtration fields (client ID, Request Date, Request Type, Request Status, etc.) in the same page to filter the list, where having these form fields would require calling the function each time and … -
Is there any alternative way of Q object?
Anyone can tell me, have any alternative way of doing it? I actually searched for a more optimized way than it. def get_queryset(self): return self.queryset.filter(Q(email="") | Q(phone="")).order_by("name") phone and email fields are: phone = models.CharField(max_length=20, blank=True) email = models.EmailField(blank=True) -
Vue.js <template> returns Uncaught SyntaxError: Unexpected token '<' when loaded in Django html files
Good day everyone. I am very new in using both django and vue.js . I am currently creating a project where I use django mainly for backend and integrate vue.js for the frontend. However, I find myself struggling so much on how to call vue.js functionalities or components in django html templates. I just couldn't crack the right steps to correctly call vue in my django project. I don't know either if I am heading the right way or maybe you can help me show the right way to do it. I already installed node.js also. Here are my codes. Django Template at users\templates\users\master.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Profile</title> {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} </head> <body> <div class="container"> {% block content %} {% endblock %} </div> </body> <script src="{% static 'js/vue.global.js' %}"></script> <script src="{% static 'js/custom-vue.js' %}"></script> <script src="{% static 'js/EventForm.vue' %}"></script> Path: C:\Users\Jun\python-project\calendarproject\static\js EventForm.vue <!-- EventForm.vue --> <template> <div class="event-form"> <!-- Your calendar event form HTML here --> <form @submit.prevent="addEvent"> <!-- Form fields for event details --> <!-- For example: Event title, date, time, description, etc. --> <!-- You can use Bootstrap or any other CSS … -
Django: Creating a custom_filter.py that will calculate total duty hours
Newbie here. Thank you in advance. I am working on a Daily Time Record(DTR) with total duty hours calculation per day and display the time-in and time-out (AM) and time-in and time-out (PM). I can already display the time-in and time-out and display the total duty hours if all of the time-in and time-out happened in the same day, but my problem is, when the time-in and time-out span across multiple day such as: # If the attendance happened on the same day, I can compute the total duty hours, in this case, it is 8 hours (hours only) [datetime.datetime(1900, 1, 1, 7, 51, 57), datetime.datetime(1900, 1, 1, 12, 0, 18), datetime.datetime(1900, 1, 1, 12, 19, 24), datetime.datetime(1900, 1, 1, 17, 0, 8)] # But, if the time-in and time-out was on separate day, I was not able to compute the total duty hours. [datetime.datetime(1900, 1, 1, 7, 57, 30)] # Time-in [datetime.datetime(1900, 1, 1, 6, 5, 36)] # Time-out # My initial plan to compute this, is to add an "end_time" and "start_time". # Initially, I want the data to be like this. # With this, I can compute each day by adding an "end_time" and "start_time" # It … -
MS AD login after a long period of being idle - Failed to match request state with session state
I had my work laptop switched off for 3 days and today when I brought it back on and ran PyCharm and went to localhost:8000 in the browser and signed in using Microsoft AD, I got : http://localhost:8000/auth/redirect?code=0.xxx# AuthSecurityError at /auth/redirect Failed to match request state with session state Request Method: GET Request URL: http://localhost:8000/auth/redirect?code=0.xxxm&state=xxxx-xxxx-xxxx-xxxx-xxxx&session_state=xxxx-xxxx-xxxx-xxxx-xxxx Django Version: 4.2.5 Exception Type: AuthSecurityError Exception Value: Failed to match request state with session state Exception Location: D:\workspace\django\projectX\env\lib\site-packages\ms_identity_web\__init__.py, line 259, in _verify_state Raised during: ms_identity_web.django.msal_views_and_urls.aad_redirect Python Executable: D:\workspace\django\projectX\env\Scripts\python.exe Python Version: 3.10.10 I don't know how all of a sudden this is happening because no code was changed in those 3 days. I even cleared cache and cookie data for the last 7 days and still in vain. Same thing happening in another browser. -
Admin user is the same django user - how to solve this
When I built my e-commerce page, I noticed that if I am logged in with user 1, when I log in with user 2 no admin, my django page is automatically logged in with user 2. I don't want this to happen. I want to continue with user 1 on the django site even if logged in with user 2 in the admin. How could this be resolved? Can someone help me please? In my views.py: def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect("store:index") elif not form.is_valid() and form.cleaned_data.get('username')!=None or form.cleaned_data.get('password')!=None: messages.error(request,"Invalid username or password.") elif form.cleaned_data.get('username')==None and form.cleaned_data.get('password')==None: messages.error(request,"Please, enter your username and password.") form = AuthenticationForm() return render(request=request, template_name="login//login.html", context={"login_form":form}) -
I have built a django app tocreate a waiting list for artisans but the registration information being entered is not being passed to the database
registration information is not going into the database I tried everything possible and it is not still working. and every other thing works perfectly and I can only add artisans information through the admin panel. Please help -
how to store other model fields in a model field in django
hi i reacently learnd django and i don't have much experience with it and i ran into a problem this is my main model class food(models.Model): name = models.CharField(max_length= 255) category = models.ForeignKey('resturant.category', models.DO_NOTHING, db_column='category') picture = models.ImageField(upload_to='/images/', default=None) rank = models.IntegerField() price = models.BigIntegerField() ingredients = models.ManyToManyField(storage) discription = models.TextField() def __str__(self) -> str : return f'{self.id} - {self.name}' and this is another model in another app class storage(models.Model): name = models.CharField(primary_key=True,max_length=255) count = models.IntegerField() type = models.CharField(max_length=255,null=True) def __str__(self) -> str : return f'{self.name}' and i want to store all the fields in storage model inside the food.ingredients field somthing like an array of objects it should be right now when i make the api of get_all_food on food model it will return [ { "name": "food_name1", "category": 2, "picture": "/images/IMAG0030.jpg", "rank": 12, "price": 450001, "ingredients": [ "rice", "onien", "vegi", "salt", "tomato", "meat", "lemon" ], "discription": "gsdgsgfsfg" }, { "name": "food_name2", "category": 3, "picture": "/mehrbanoo/images/IMAG0075.jpg", "rank": 28, "price": 50000, "ingredients": [ "rice", "vegi", "beans", "lemon" ], "discription": "ssdafafadsada" } ] but i need it to be like : [ { "name": "food_name2", "category": 3, "picture": "/mehrbanoo/images/IMAG0075.jpg", "rank": 28, "price": 50000, "ingredients": [ { "rice",2,gr } { "vegi",3,gr } … -
Django count() with a prefetch_related query seems not to work
I am working in a Django project and I could not get to work the count() function with Prefetch. I have 20 orders but only 17 has its payout='available'. If I try to get the count() after filter inside a Prefetch Query: order = Order.objects.filter(vendors__in=[vendor.id], is_ordered= True).order_by('-created_at') promise_ordered_products_orders = order.prefetch_related( Prefetch( 'orderedproductorders', queryset = OrderedProduct.objects.filter(product__vendor__id=vendor.id, payout='available') ) ) print(promise_ordered_products_orders.count()) I get 20 orders as the count() function result i.e all orders. But it should be only 17. I already manage to solve it with for loop to a list =[] and len(). I was wondering if there is anyway to get count() to work inside for the 'orderedproductordes' and not for all orders in the Prefetch Query.