Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django calling a function
Hello stackoverflow im trying to learn django on my own with taking an online course and im pretty sure im doing all the things right but program keep reporting me an error called ( the class has no object attribute ) I know it means what its says but problem is i think we are calling a function to do work with this class not calling an attribute form the class as you can see in the following code: class Article(models.Model): title = models.CharField(max_length=100) body = models.TextField() view = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add= True) updated_at = models.DateTimeField(auto_now= True) published_at = models.DateTimeField(default= timezone.now) def __str__(self): return self.title this is the code for the class and the following code is for the section which makes problems for me: def index(request): articles = Article.objects.order_by('created_at')[:10] return render(request , 'index.html' , { 'title' : 'Articles Page', 'articles' : articles }) def single(request , article_id): articles = Article.objects.get(id= article_id) return render(request , 'single.html' , { 'title' : articles.title , 'articles' : articles }) Both << Article from def index and def single >> giving me this error "Article has no 'objects' member." any tips? -
Django Success URL Gets Appended To Middleware Redirect URL Instead of Redirecting To Success URL
I have a form with a username field on it located at /accounts/choose-username/. views.py from django.views.generic import FormView from .forms import ChooseUsernameForm from django.contrib.auth import get_user_model User = get_user_model() class ChooseUsernameView(FormView): template_name = 'registration/choose-username.html' form_class = ChooseUsernameForm success_url = 'accounts/profile/' # <------------- def form_valid(self, form): """If the form is valid, redirect to the supplied URL.""" print(form.cleaned_data['username']) print(self.request.user) user = User.objects.get(email=self.request.user) user.username = form.cleaned_data['username'] user.save() return super().form_valid(form) middleware.py from django.shortcuts import redirect, reverse class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) if request.user.is_authenticated: if request.user.username is None: print(request.path) if not request.path == reverse('choose_username'): return redirect(reverse('choose_username')) return response When I submit the form, my url is accounts/choose-username/accounts/profile/ I want it to be accounts/profile/ MIDDLEWARE settings.py looks like this: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'accounts.middleware.SimpleMiddleware', # <--- 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] My Question Why does my success URL get appended to my accounts/choose-username/ URL? How can I fix it? -
How to update related model fields in Django
I have two models (purchase and stock), I Want when i purchase an item the quantity field in stock to be updated. (eg. i have 2 Mangoes in stock and i purchase 3 Mongoes, i want the updated stock to be 5 Mangoes) My Models class Stock(models.Model): product = models.ForeignKey(Products, null=True, blank=True, on_delete = models.SET_NULL) stock_date = models.DateField(null=True, blank=True) quantity = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True) buying_price = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True) class Purchase(models.Model): product = models.ForeignKey(Stock, null=True, blank=True, on_delete = models.SET_NULL) order_date = models.DateField(null=True, blank=True) quantity = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True) buying_price = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True) Can anyone help please! -
Django testing - client.cookies empty if there was another test case before
I'm testing my Django application with Selenium in Docker. I encounter a peculiar thing related to cookies availability (I use cookies to authenticate in my tests). Here is the code that works: from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from users.models import CustomUser class SomeTest(StaticLiveServerTestCase): @classmethod def setUpClass(cls): cls.host = "web" # Docker service name super().setUpClass() CustomUser.objects.create_user(username="user", password="password") def setUp(self): self.browser = webdriver.Remote("http://selenium:4444/wd/hub", DesiredCapabilities.FIREFOX) self.browser.get(self.live_server_url) def tearDown(self): self.browser.quit() def test2(self): self.client.login(username="user", password="password") cookie = self.client.cookies["sessionid"] ... However, when I insert there another test case before test2, let it be something as simple as def test1(self): pass then the code crashes with the following error: Traceback (most recent call last): File "/home/mysite/functional_tests/test.py", line 28, in test2 cookie = self.client.cookies["sessionid"] KeyError: 'sessionid' So the only difference between the working and not-working code is a dummy test function, but what does it change? As far as I know the setUp and tearDown methods make sure that the "environment" is the same for every test case, no matter what happens in other test methods and here it clearly depends on the (non-)existence of other test cases before running my test... Is there something I misunderstand? Or is it some … -
Django Admin Inline hit database multiple times
DjangoVersion:2.1.7 PythonVersion:3.8.2 I have a StoreLocation model which has ForeignKeys to Store, City and Site (this is the default DjangoSitesFramework model). I have created TabularInline for StoreLocation and added it to the Store admin. everything works fine and there isn't any problem with these basic parts. now I'm trying to optimize my admin database queries, therefore I realized that StoreLocationInline will hit database 3 times for each StoreLocation inline data. I'm using raw_id_fields, managed to override get_queryset and select_related or prefetch_related on StoreLocationInline, StoreAdmin and even in StoreLocationManager, i have tried BaseInlineFormsSet to create custom formset for StoreLocationInline. None of them worked. Store Model: class Store(models.AbstractBaseModel): name = models.CharField(max_length=50) description = models.TextField(blank=True) def __str__(self): return '[{}] {}'.format(self.id, self.name) City Model: class City(models.AbstractBaseModel, models.AbstractLatitudeLongitudeModel): province = models.ForeignKey('locations.Province', on_delete=models.CASCADE, related_name='cities') name = models.CharField(max_length=200) has_shipping = models.BooleanField(default=False) class Meta: unique_together = ('province', 'name') def __str__(self): return '[{}] {}'.format(self.id, self.name) StoreLocation model with manager: class StoreLocationManager(models.Manager): def get_queryset(self): return super().get_queryset().select_related('store', 'city', 'site') class StoreLocation(models.AbstractBaseModel): store = models.ForeignKey('stores.Store', on_delete=models.CASCADE, related_name='locations') city = models.ForeignKey('locations.City', on_delete=models.CASCADE, related_name='store_locations') site = models.ForeignKey(models.Site, on_delete=models.CASCADE, related_name='store_locations') has_shipping = models.BooleanField(default=False) # i have tried without manager too objects = StoreLocationManager() class Meta: unique_together = ('store', 'city', 'site') def __str__(self): return '[{}] {} … -
AngularJS Retrieve nested JSON
I have a loop which loops through my dictionary: for p in place.values(): print(p) jString = json.dumps(p.__dict__) The output looked like this: {"Place": "Liberty City", "time": [{"07:00": 116}, {"08:00": 120}, ...]} I did a print(place.items()). This is the output: `dict_items([('Liberty City', <myapp.models.Place object at 0x0930C150>), ('San Andreas', <myapp.models.Place object at 0x0930C390>`)...] Why am I able to get the Json string but unable to get the value of the dictionary? This is my model: class Location: def __str__(self): s = ['{}\t{}\t{}'.format(k, t[k], self.name) for t in self.times for k in t.keys()] return '\n'.join(s) -
Why depth values in serializer Meta class not work?
I have a serializer serializer.py class VendorManagementUpdateSerializer(serializers.ModelSerializer): ... parent = serializers.PrimaryKeyRelatedField(queryset=Vendors.objects.all(), required=False, allow_null=True) ... class Meta: model = Vendors fields = (..., ...., 'parent', ) depth = 1 class VendorToFrontSerializer(serializers.ModelSerializer): class Meta: model = Vendors fields = ('pk', 'vendor_name') But response data after PUT request return only id fields. And I need to get all the fields out of the serializer VendorToFrontSerializer ('pk', 'vendor_name') Isn't that what depth is used for? I know I can use this type of serializer parent = VendorToFrontSerializer() But the problem is that I use partial_update and when I send this field to the PUT request { "parent":123 } what I get is { "parent": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got int." ] } } How do I do it right? -
Django Graphene form validation with integer field
Here's my simple scenario. I have a model that has two mandatory fields name and age: class Person(models.Model): name = models.CharField(max_length=256) age = models.PositiveIntegerField() I'm using Django model form with Graphene class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('name', 'age') class PersonType(DjangoObjectType): class Meta: model = Person class PersonMutation(DjangoModelFormMutation): class Meta: form_class = PersonForm class Mutation(graphene.ObjectType): person_mutation = PersonMutation.Field() Lets say a person fills age field but not name field. I can then send a mutation query mutation { personMutation(input: {age: 25, name: ""}) { errors { field messages } } } I get the following response, which is exactly what I want. This response is easy to go through and I get name field validation message. { "data": { "personMutation": { "errors": [ { "field": "name", "messages": [ "This field is required." ] } ] } } } But what if the user fills name but not age? What kind of mutation query should I make? If I make mutation { personMutation(input: {name: "my name"}) { errors { field messages } } } I get the response below. That is a horrible message, I can't show that to user. Also response json format is different than before. … -
Parameters for Post request for form-data in pyresttest
I want to check whether my api is working through pyresttest where we can check testcases, but how can I check testcase to check form-data. My postman looks like: I want to test the api in pyresttest. and where will I keep the file to check it in pyresttest ? -
Django: The page isn't redirecting properly error
I'm getting `the page isn't redirecting properly' coming up in my browser. I'm trying to move an app to be in a sub-folder of another app (because logically it is a special case of that app). This code is causing the loop, but I do not understand why. if administration_instance.study.instrument.form in ['CAT'] : return redirect('cat_forms:administer_cat_form', hash_id=hash_id) My main urls.py have this line: url(r'^form/', include('cdi_forms.urls')), My cdi_forms.urls has this line: url(r'fill/(?P<hash_id>[0-9a-f]{64})/$', views.administer_cdi_form, name='administer_cdi_form'), #I've included this line because it is the url being called in the loop path('cat/', include(('cdi_forms.cat_forms.urls', 'cat_forms'), namespace="cat_forms")), And my cdi_forms.cat_forms.urls has path('fill/<hash_id>/', views.AdministerAdministraionView.as_view(), name='administer_cat_form'), This generates a url /form/cat/fill/614764fa0f135073bc6166ab560882da3a4ed674fcd7f05030583daa1e637230/ which is correct but it is calling the initial function which is at url /form/fill/614764fa0f135073bc6166ab560882da3a4ed674fcd7f05030583daa1e637230/. The difference is the inclusion of cat in the former. Why is it looping? -
How can I disable/remove authorize button in swagger using django
I'm unable to remove authorize button in swagger using Django -
like and comment section: in django
I like to put like and comment section with some info like no. of likes and comment and also show user who comment on it in django project but don't know how can anyone help me her is my html code {% for post in post %} <article class="media mt-4"> <div class="media-body"> <img class="rounded-circle article-img" id="dp" src="{{ post.author.profile.image.url }}"> <div class="article-metadata"> <a class="mr-2" href="{% url 'Love Travel-User' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'User-Posts-Details' post.id %}">{{ post.title }}</a></h2> <img src="{{ post.img.url }}" class="article-img"> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} here views.py class PostListViews(ListView): model = Post template_name = 'userpost/posts.html' context_object_name = 'post' ordering = ['-date_posted'] paginate_by = 7 and models.py class Post(models.Model): title= models.CharField(max_length=100) img = models.ImageField(upload_to='pics') content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author= models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('User-Posts-Details', kwargs={'pk': self.pk}) anyone can please help me? -
SECRET_KEY setting must not be empty when I set LANGUAGES
Hi here is the error raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. when I remove LANGUAGES from settings file, Then Its running , other wise giving the error, I tried but not able to resolve it please help. Code Structure - config-settings-base.py, local.py, production.py. I set LANGUAGES in base.py. here is the code of base.py setting ``` import os from django.utils.translation import gettext as _ import environ from django.urls import reverse_lazy env = environ.Env() ROOT_DIR = environ.Path(__file__) - 3 APPS_DIR = ROOT_DIR.path('userpeek') READ_DOT_ENV_FILE = env.bool('DJANGO_READ_DOT_ENV_FILE', default=True) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django.settings') if READ_DOT_ENV_FILE: # OS environment variables take precedence over variables from .env env_file = str(ROOT_DIR.path('.env')) env.read_env(env_file) ENV = env application_name = env('APPLICATION_NAME') LOG_DIR = env('LOG_DIR') FILE = application_name + '.log' DEBUG = env.bool('DJANGO_DEBUG', False) # Local time zone. Choices are # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # though not all of them may be available with every OS. # In Windows, this must be set to your system time zone. # SECURITY WARNING: keep the secret key used in production secret! USE_THOUSAND_SEPARATOR = True # DATABASES # ------------------------------------------------------------------------------ # DATABASE_ROUTERS = ['manager.router.DatabaseAppsRouter'] # DATABASE_ROUTERS = ['klm.application.router.FailoverRouter'] DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': … -
Is it possible to catch response in a React website which is opening via redirect from another website?
Consider the scenario where I have created a site in Django(website A) and another site in React(website B). I have a button on website A which redirects to website B. While redirecting I am setting up some headers which I want to retrieve from website B when it gets redirected. Is this situation plausible? -
module 'mysite.asgi' has no attribute 'channel_layer' on Heroku and Django application
I'm trying to deploy a Django application to Heroku but i keep getting the following error: 2020-04-13T08:45:00.134349+00:00 app[web.1]: Traceback (most recent call last): 2020-04-13T08:45:00.134389+00:00 app[web.1]: File "/app/.heroku/python/bin/daphne", line 8, in <module> 2020-04-13T08:45:00.134519+00:00 app[web.1]: sys.exit(CommandLineInterface.entrypoint()) 2020-04-13T08:45:00.134524+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/daphne/cli.py", line 191, in entrypoint 2020-04-13T08:45:00.134697+00:00 app[web.1]: cls().run(sys.argv[1:]) 2020-04-13T08:45:00.134699+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/daphne/cli.py", line 252, in run 2020-04-13T08:45:00.134891+00:00 app[web.1]: application = import_by_path(args.application) 2020-04-13T08:45:00.134913+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/daphne/utils.py", line 14, in import_by_path 2020-04-13T08:45:00.135028+00:00 app[web.1]: target = getattr(target, bit) 2020-04-13T08:45:00.135056+00:00 app[web.1]: AttributeError: module 'mysite.asgi' has no attribute 'channel_layer Here is my Procfile: web: daphne WR.asgi:channel_layer --port $PORT --bind 0.0.0.0 -v2 And here is how i defined Redis on my settings.py: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('https://mytestapp1.herokuapp.com/', 6379)], 'capacity': 1500, 'expiry': 2, }, }, } Can anyone help me find what i'm doing wrong? Can it be the fact that i have to add the Redis heroku addon to my app? -
how to reinstall Django
for some reasons i removed django first i entered >> import django >> django.__path__ and then i entered sudo rm -r path in terminal. and now when im trying to reinstall it i enter these commands $ sudo apt-get update $ sudo apt-get install python3-django i see Reading package lists... Done Building dependency tree Reading state information... Done python3-django is already the newest version (1:1.11.11-1ubuntu1.8). 0 upgraded, 0 newly installed, 0 to remove and 5 not upgraded. and then i enter django-admin --version i see Traceback (most recent call last): File "/usr/local/bin/django-admin", line 5, in from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' what should i do to reinstall it? please help -
post_save signal for specific Profile model for user registration
I have 2 profile models (Profile1 and Profile 2) with a one-to-one relationship with the django User class. I have 2 separate registration forms, 2 different signals, 2 different views / routes for each model. When I register a user with Profile1, it creates the Profile1 instance but it also creates a Profile2 instance. How can I specify the signal to use based on the type of user signing up? Here is my signals.py for Profile1 @receiver(post_save, sender=User) def create_profile1(sender, instance, created, **kwargs): if created: Profile1.objects.create(customer=instance) @receiver(post_save, sender=User) def save_profile1(sender, instance, created, **kwargs): instance.profile1.save() Here is my signals.py for Profile2 @receiver(post_save, sender=User) def create_profile2(sender, instance, created, **kwargs): if created: Profile2.objects.create(customer=instance) @receiver(post_save, sender=User) def save_profile2(sender, instance, created, **kwargs): instance.profile2.save() -
Update field in unrelated table by spanning relationships using Django ORM
I am using Django 3.0.4. I have 6 tables (Vehicle, Tracker, Driver, Contract, Account and Invoice). There are Many Invoices for each Account(1-M). A single Account is opened for every single Contract(1-1). Each Contract is comprised of a Driver and a Vehicle and Driver-Vehicle combination can have only 1 Contract. Each Vehicle is fitted with a single Tracker(1-1). I intend to check the status of the Invoice(I have done this already) and navigating from this particular record of Invoice I need to find the particular Vehicle inorder to update the status of the Tracker. Tracker has no relation to Invoice and select_related does not seem to work. Your assistance is appreciated. class Vehicle(models.Model): registration = models.CharField(max_length=7, unique = True) make = models.CharField(max_length=16) model = models.CharField(max_length=16) class Tracker(models.Model): vehicle = models.OneToOneField('Vehicle', on_delete=models.CASCADE) msisdn = models.PositiveIntegerField() status = models.CharField(max_length=16) class Driver(models.Model): first_name = models.CharField(max_length=16) middle_name = models.CharField(max_length=16, blank=True) last_name = models.CharField(max_length=16) class Contract(models.Model): vehicle = models.ForeignKey('Vehicle', on_delete=models.CASCADE) driver = models.ForeignKey('Driver', on_delete=models.CASCADE) start_date = models.DateTimeField(auto_now=False, auto_now_add=False) end_date = models.DateTimeField(auto_now=False, auto_now_add=False) class Account(models.Model): contract = models.OneToOneField('Contract', on_delete=models.CASCADE) weekly_amount = models.PositiveSmallIntegerField() weeks = models.PositiveSmallIntegerField() paid_amount = models.PositiveIntegerField() class Invoice(models.Model): account = models.ForeignKey('Account', on_delete=models.CASCADE) amount = models.PositiveIntegerField() status = models.CharField(max_length=16, choices=INVOICE_STATUS, default=UNPAID) -
How to display separate titles on each page in Django
I have a Django website where I have separated the html files into a base.html file as so: {% include 'head.html' %} <body> {% include 'nav.html' %} {% block content %} {% endblock content %} {% include 'footer.html' %} {% include 'scripts.html' %} </body> </html> Due to including head.html, the title on each page is the same, since head.html has only 1 title. Here is the head.html file: <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/materialize.css' %}"> <link rel="stylesheet" href="{% static 'css/materialize.min.css' %}"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <link rel="stylesheet" href="{% static 'css/custom.css' %}"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <title>mytitle</title> </head> But i want to display different titles for different pages and I dont know how to. Anyone have any idea? -
How to trim the length of a field's value to max_length in Django?
Suppose I have the following Django model: class City(models.Model): name = models.CharField(max_length=5, null=True, blank=False) When doing City(name='Sapporo').save(), is there a way to automatically trim the length of name to max_length such that "sappo" gets saved in database instead of throwing an error? I don't want to manually check the lengths and trim it myself since I have many charFields fields in many tables, all with different max lengths. -
Are there any 'sorl-thumbnail' like Django packages that can do image processing client-side?
I was wondering if you guys are aware of any sorl-thumbnail like (large-scale) Django packages that can do resizing (image processing) client-side. -
using mock on djstripe signal
im having trouble mocking a djstripe web hook signal. The signal in question is: @webhooks.handler("charge.dispute.created") I need to mock this signal being sent so i can test the following method. I use this signal to notify administration that a dispute has been raised. Here is a link to the page on github that contains djstripes signal code: https://github.com/dj-stripe/dj-stripe/blob/master/djstripe/signals.py Here is the method used on the djstripe handler @webhooks.handler("charge.dispute.created") def charge_dispute_created(event, **kwargs): print(event) details = event.data.get("object") charge_id = details['charge'] charge = stripe.Charge.retrieve( charge_id,) order_pk = charge['metadata']['order'] buyer_email = charge['metadata']['buyer'] buyer = User.objects.get(email=buyer_email) seller_email = charge['metadata']['seller'] seller = User.objects.get(email=seller_email) order = Order.objects.get(pk=order_pk) payment_intent = details['id'] #send notification to buyer via notification and email notify.send(sender=order.advert, recipient=buyer, verb=' - A dispute has been raised on this listing due to the payment being flagged. Please contact customer support.', action_object=order) send_mail( 'Payment disputed', 'Unfortunately your payment for %s has had a dispute filed, a dispute on this order has been raised. Please contact your card issuer.' % order.advert, 'accounts@foxlisted.com.au', [buyer_email], fail_silently=False) Here is the test( i haven't included the user creation and order set up to save space: @patch('djstripe.signals.WEBHOOK_SIGNALS[("charge.dispute.created")].send') @patch('stripe.Charge.retrieve') @patch('notifications.signals.notify.send') def test_charge_dispute_created_notifys_users_when_order_completed(self, handler_mock, notify_mock, retrieve_mock): obj = {'charge' : 'ch_1234'} charge = {'metadata' : {'order' … -
Edit a formset in django
In my django app I am trying to understand many to many relationship and I am using formset to store the data like this: Views.py def Team_Form(request): if request.POST: form = TeamForm(request.POST) form.player_instances = PlayerFormset(request.POST) if form.is_valid(): team= Team() team.tname= form.cleaned_data['tname'] team.save() if form.player_instances.cleaned_data is not None: for item in form.player_instances.cleaned_data: player = Player() player.pname= item['pname'] player.hscore= item['hscore'] player.age= item['age'] player.save() team.player.add(player) team.save() else: form = TeamForm() return render(request, 'packsapp/employee/new.html', {'form':form}) Models.py class Player(models.Model): pname = models.CharField(max_length=50) hscore = models.IntegerField() age = models.IntegerField() def __str__(self): return self.pname class Team(models.Model): tname = models.CharField(max_length=100) player= models.ManyToManyField(Player) def __str__(self): return self.tname Forms.py class PlayerForm(forms.Form): pname = forms.CharField() hscore= forms.IntegerField() age = forms.IntegerField() PlayerFormset= formset_factory(PlayerForm) class TeamForm(forms.Form): tname= forms.CharField() player= PlayerFormset() What I failed to understand is that how to edit the formset that I just Saved or to better phrase the question, How to pass the saved instance to the formset to edit it ? -
How to count objects from database filtered by a choice field in django?
I have Porumbei model and it has gender field. In template I must render the number of Porumbei of each gender. For example: Male= x Porumbei, Female= y Porumbei and Unknown = z Porumbei. My model class Porumbei(models.Model): SEXE = [ ('Mascul', 'Mascul'), ('Femelă', 'Femelă'), ('Pui', 'Pui') ] ... gender = models.CharField(max_length=6, choices=SEXE, db_index=True) ... For Total I have: total = Porumbei.objects.count() Below is what I have now: @staticmethod def masculi(crescator=None): """ Numarul de masculi din sistem """ mascul = Porumbei.objects.filter(gender="Mascul", is_active=True, crescator=crescator) return len(mascul) @staticmethod def femele(crescator=None): """ Numarul de femele din sistem """ femela = Porumbei.objects.filter(gender="Femelă", is_active=True, crescator=crescator) return len(femela) @staticmethod def pui(crescator=None): """ Numarul de pui din sistem """ pui = Porumbei.objects.filter(gender="Pui", is_active=True, crescator=crescator) return len(pui) These functions gets me what I want but from my point of view, are not well optimized. This will end up in three similar queries as I saw in django debug toolbar. My question is, how can I get the number of each gender in only one query. Is it possible with another method or this function can be optimized to do a single query in database? I must mention that with the number of each gender, arithmetic operations must be … -
Group objects that share a field value in common in the same line in Django admin result list
I have a model Allocation in which several objects can share the same datetime field. In the admin page with the result list all objects are in a separate line but it makes the list difficult to read, so my question is what could be the solution to group these objects in a single line? I have no idea how to implement such customization and if there is filter to do that as I'm new to Django. I did a try with fieldsets but it modify the object page not the page with the result list. I'm afraid this is not that easy to implement but I wanted to ask. Thanks! class Allocation(models.Model): portfolio = models.ForeignKey( Portfolio, on_delete=models.CASCADE, related_name='allocation', null=True ) datetime = models.DateTimeField( null=True ) instrument = models.CharField( max_length=10, null=True ) This is what I have in the admin list result page: | Portfolio | Datetime | Instrument | ------------------------------------------------ port1 2020/01/01 AAPL port1 2020/01/01 MSF But what I would like is this: | Portfolio | Datetime | Instrument1 | Instrument2 | ------------------------------------------------------------------- port1 2020/01/01 AAPL MSF