Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Elegantly spread single Django model across multiple tables?
There's plenty of document and discussion for having multiple models share fields in a parent class/table using "concrete" or "multi-table" inheritance: class Place(models.Model): ... class Restaurant(Place): ... However, I can't find much on the inverse use-case: splitting the fields of a single model across multiple tables to save the cost of loading wide columns except when you actually need them. Consider the following scenario: class Person_Profile(models.Model): ...lots of fields... class Person_Preferences(models.Model): ...lots of fields... class Person(Person_Profile, Person_Preferences): ...small set of core fields... What works: When you create a Person, the other two objects are automatically created and linked for you. You can access profile and preference fields directly on Person. (person.some_field) The only thing I'm missing is how to elegantly control when Django loads the fields from the parent table, since currently, loading a Person with p = Person.objects.first() results in all three tables being joined and selected by default. -
How to separate the image model from the other models and create relation between it and others and create more than one image for a object
I want to make an image model and some other models that may have several photos for each object. How can I implement it in Django and Rest Framework? -
I receive an error while migrating my models to a database
I get such an error while migrating to a database: return Database.Cursor.execute(self, query) django.db.utils.OperationalError: foreign key mismatch - "user_auth_customer" referencing "user_auth_profile" I have checked Foreign_Keys of my models and they look good. I have no idea why I receive that error :( Please, help me out here. class Customer(AbstractUser): USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) profile = models.OneToOneField("Profile", related_name="user_profile", on_delete=models.CASCADE, null=True) first_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50, null=True, blank=True) username = models.CharField(max_length=30, null=True, blank=True) phone = models.CharField(max_length=10, default='', null=True, blank=True) email = models.EmailField(validators=[validators.EmailValidator()], unique=True) password = models.CharField(max_length=100, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) @staticmethod def get_customer_by_email(email): try: return Customer.objects.get(email=email) except: return False def isExists(self): if Customer.objects.filter(email=self.email): return True return False class Meta: verbose_name = 'Customer' verbose_name_plural = 'Customers' class Profile(models.Model): first_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50, null=True, blank=True) phone = models.CharField(max_length=10, default='', null=True, blank=True) email = models.EmailField(primary_key=True, unique=True, validators=[validators.EmailValidator()]) password = models.CharField(max_length=100, null=True, blank=True) # Add a photo field owner = models.OneToOneField(Customer, related_name='profile_owner', on_delete=models.SET_NULL, null=True) username = models.CharField(max_length=30, null=True, blank=True, validators=[UnicodeUsernameValidator()]) date_created = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Profile' verbose_name_plural = 'Profiles' if you need any else details, I can provide you with those in the comments. -
Django hidden input being rendered as <td> in html
I'm using a modelformset to allow the user to add/edit/delete food item's on their restaurant's menu. FoodItemFormset = modelformset_factory(FoodItem, fields = '__all__', can_delete = True) I'm then iterating over all of the forms in my template and displaying them in a table: <table> <tr> <th>Food Item</th> <th></th> <!-- empty <th> lines up with hidden input field --> <th>Delete</th> </tr> {% for form in food_formset %} <tr> {% for field in form %} <td>{{ field }}</td> {% endfor %} </tr> {% endfor %} </table> <input type="submit" name="" value="Submit"> However, that can_delete attribute does not only lead to a checkbox being rendered, it also renders the hidden field containing the object's id as an actual table element, leading to an empty gutter between the tables contents. <td><input type="text" name="form-0-name" value="Mozzarella Sticks" maxlength="200" id="id_form-0-name"></td> <td><input type="hidden" name="form-0-id" value="2" id="id_form-0-id"></td> <!-- this just looks like an empty gutter --> <td><input type="checkbox" name="form-0-DELETE" id="id_form-0-DELETE"></td> Is there a way to get around this? Thanks for any help. -
In Django Debug request url shown as http instead of https
sorry if the message reads weird: it was originally intended for django support. Let me give a little bit of context to the issue. Recently, my team has upgraded the packages of our app, one of those packages being Django, from 2.2 to 3.2.13. The only thing in this commit are the changes of packages. There is an endpoint on our app that has been tested on a local host and deployed to a dev server and a QA/Test server, and has worked as intended. However, this endpoint fails on our prod deployment, with the ssl issue that you are seeing before you. I was wondering if this has anything to do with the request URL being shown as an http rather than an https. As you can see, the page that we are on shows it’s an https, differing from the Django debug which is showing as an http. Question 1: Am I correct to assume the request being made is an http even though the URL shows as an https? My hypothesis is that this issue is only manifesting itself in production because our prod environment wont allow traffic over http. If this is the case, I am … -
Django keeps replacing content on the view
I have multiple text files in a folder, which all of them created dynamically from Cisco Switches. I want to read each file and display on the web. So I have this code: def idf(request): context = {} all_files = os.listdir("devices/") for i in all_files: with open(i, 'r') as readFile: switch_ports = readFile.readlines() print(switch_ports) readFile.close() context.update({'switch_ports': switch_ports}) return render(request, 'idf.html', context) The problem is, it loops through the function, and only renders the last file. So it is basically replacing the content. How can I keep all of them? So they just keep appending to the last file? Here is the template: {% block everyDevice %} {% block switch_ports %} <h1>{{ everyDevice }}</h1> {% for result in switch_ports %} <p>{{ result }}</p> {% endfor %} {% endblock %} {% endblock %} </main> -
Open an image in python and upload it to S3
I was trying to open a file/image in python/django and upload it to s3 but I get different errors depending on what I try. I can get it to work when I send the image using the front end html form but not when opening the file on the back end. I get errors such as "'bytes' object has no attribute 'file'" Any ideas how to open an image and upload it to s3? I wasn't sure if I was using the correct upload function, but it worked when I received the file from an html form instead of opening it directly. image = open(fileURL, encoding="utf-8") S3_BUCKET = settings.AWS_BUCKET session = boto3.Session( aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, ) s3 = session.resource('s3') s3.Bucket(S3_BUCKET).put_object(Key='folder/%s' % fileName, Body=image) Thanks. -
Django: How to make a simple editable text? [closed]
I have a a simple information page, but I need to change the information a lot. I want to do this from the admin side. I can do this with a model, but I don't need to add or remove items. How can I do this? -
Django image cropping in ilineformset
I'm trying to make inline formset which one field gets chopped image as one of parameters. I have already done cropping with help of some tutorials but it works only with single model, when I tried to transform it to inline formset, new image is being saved in raw form - cropping isn't getting applied. models look like that: class Product(models.Model): name = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE) availability = models.IntegerField() price = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.name def get_image_url(self): return Image.objects.get(product=self).file.url class Photo(models.Model): file = models.ImageField(upload_to=getImageURL2, default="static/default.png") uploaded = models.DateTimeField(auto_now_add=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return str(self.pk) forms: class PhotoForm(forms.ModelForm): class Meta: model = Photo fields = ('file',) ProductPhotoInlineFormset = inlineformset_factory( Product, Photo, fields=('file',), form=PhotoForm, extra=1, can_delete=False, ) views: def ProductCreateView(request): context = {} created_product = None form = ProductForm() if request.method == 'POST': print(request.POST) form = ProductForm(request.POST) if form.is_valid(): created_product = form.save() print("Successfully created new product: {}".format(created_product)) else: print("form is not valid") print(form.errors) print(form.non_field_errors()) context['form'] = form created_images = [] formset = ProductPhotoInlineFormset() if request.method=='POST': formset = ProductPhotoInlineFormset(request.POST or None, request.FILES or None, instance=created_product) if formset.is_valid(): for f in formset: image = f.save() created_images.append(image) print("Successfully created new imagest: {}".format(image)) return JsonResponse({'message': 'works'}) else: print(formset.errors) … -
Dropdown filtering objects in django template using javascript
I have a table that shows details about all the assets. I want the records in the table to be filtered on the basis of different attributes of the table. For now I have tried to create a filter on currentOwner field using JavaScript, but it is not working. Here is the html file: {% extends "assets/base.html" %} {% block content %} <div class="container"> <legend class="border-bottom mb-4">Hello {{ request.user }}</legend> </br> <table class="table" id="admin-asset-table"> <tr> <th>Asset ID</th> <th>Asset Type</th> <th>Asset Name</th> <th>Brand</th> <th>Is Active</th> <th> <select id="searchddl" onclick="searchOwner();"> <option disabled="true" selected>-- Current Owner --</option> {% for user in users %} <option value="{{asset.currentOwner}}"> {{user.username}} </option> {% endfor %} </select> </th> <!-- <th>Current Owner</th> --> </tr> {% for asset in assets %} <tr> <td><a href="{% url 'asset-update' id=asset.id%}">{{ asset.id }}</a></td> <td>{{ asset.asset_type }}</td> <td>{{ asset.asset_name }}</td> <td>{{ asset.brand }}</td> <td>{{ asset.isActive }}</td> <td>{{ asset.currentOwner }}</td> </tr> {% endfor %} </table> </div> <script type="text/javascript"> function searchOwner() { var input,table,tr,td,filter,i; input=document.getElementById("searchddl"); filter=input.value.toUpperCase(); table=document.getElementById("admin-asset-table"); tr=table.getElementsByTagName("tr"); for(i=0; i<tr.length; i++) { td=tr[i].getElementsByTagName("td")[3]; if(td) { displaydata=td.innerText; if(displaydata.toUpperCase().indexOf(filter)>-1) { tr[i].style.display=""; } else { tr[i].style.display="none"; } } } } </script> {% endblock content%} Please let me know what is wrong with this. Also let me know if there is any … -
Count number of times object appears in Foreign Key with filter
My models are as so: class TeamMember(models.Model): name = models.CharField(max_length=500) class Opportunity(models.Model): name = models.CharField(max_length=500) date_created = models.DateTimeField( auto_now=True) team_lead = models.ForeignKey('TeamMember', blank = False, related_name = 'lead_opps') I need to create a list of team member names with the number of opportunities they have taken part of ordered by the count. This is straightforward using the method below, however- I also need to limit the opportunities by date range. So to summarize, I need to create a list of team members with the number of opportunities they have taken lead on within a time range. How do I add a filter to the opps being counted within the annotation? Here is what I have so far: TeamMember.objects.annotate(num_opps = Count('lead_opps')).order_by('-num_opps')[0].num_opps -
OperationalError at /register no such table: class_profile
I am getting this error when creating new users. Any help would be appreciated, thank you. I haven't added anything in my settings.py like AUTH_USER_MODEL = 'class.User' My models.py: from pyexpat import model from django.contrib.auth.models import User from django.core.checks.messages import CheckMessage from django.db import models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) institution = models.CharField(max_length = 100) bio = models.TextField(max_length=300) def __str__(self): return f'{self.user.username} Profile' My views.py: def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) profile_form = ProfileForm(request.POST, request.FILES) if form.is_valid() and profile_form.is_valid(): user = form.save() profile = profile_form.save(commit=False) profile.user = user profile.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() profile_form = ProfileForm() return render(request, 'class/register.html', {'form': form, 'profile_form': profile_form}) -
What is causing this error when i try to deploy my django project to heroku
ERROR: Ignored the following versions that require a different python version: 1.9.5 Requires-Python >=2.7, !=3.0., !=3.1., !=3.2., !=3.3., <3.7 remote: ERROR: Could not find a version that satisfies the requirement pywin32==304 (from versions: none) remote: ERROR: No matching distribution found for pywin32==304 remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to *************. -
Validation error message isn't showing in django
The validation error Password not matched isn't showing if I separately access the fields like {{form.psrd}} (password field) and {{form.rpsrd}} (Re-Type password field). But error message shows if I use {{form.as_p}}. This is my forms.py: from django import forms class formdata(forms.Form): name = forms.CharField( max_length=20, widget=forms.TextInput(attrs={'class': 'input'})) email = forms.EmailField(widget=forms.TextInput(attrs={'class': 'input'})) psrd = forms.CharField(min_length=8, widget=forms.PasswordInput( attrs={'class': 'input'}), label='Password') rpsrd = forms.CharField(min_length=8, widget=forms.PasswordInput(attrs={'class': 'input'}), label='Re-Type Password') def clean(self): cleaned_data = super().clean() p = self.cleaned_data['psrd'] rp = self.cleaned_data['rpsrd'] if p != rp: raise forms.ValidationError('Password not matched') Body of regi.html : <body> <form method="post">{% csrf_token %} <label> <p class="label-txt">ENTER YOUR NAME</p> {{form.name}} <div class="line-box"> <div class="line"></div> </div> </label> <label> <p class="label-txt">ENTER YOUR EMAIL</p> {{form.email}} <div class="line-box"> <div class="line"></div> </div> </label> <label> <p class="label-txt">ENTER YOUR PASSWORD</p> {{form.psrd}} <div class="line-box"> <div class="line"></div> </div> </label> <label> <p class="label-txt">RE-ENTER YOUR PASSWORD</p> {{form.rpsrd}} <div class="line-box"> <div class="line"></div> </div> </label> <button type="submit">submit</button> </form> </body> -
Provide request data from view into serializer ModelViewSet Django
I try to make a custom list function inside ProductViewSet because I need to download an extra field - the highest product price in database. How can I provide the request argument from def list into serializer? I mean right now I get error 'NoneType' object has no attribute 'user' in this line: if request.user.is_authenticated. So how can I fix it that he can read self.context.get('request') correctly? class ProductViewSet(viewsets.ModelViewSet): ... def list(self, request): queryset = Product.objects.all() serializer = ProductSerializer(queryset, many=True) return Response(serializer.data) class ProductSerializer(serializers.ModelSerializer): ... class Meta: model = Product ... def get_is_followed(self, obj): request = self.context.get('request') if request.user.is_authenticated: return Product.objects.filter(id=obj.id, followers=request.user.id).exists() I want to work it like a default ModelViewSet list but with an extra field. -
Django not showing image from api
So i'm trying to render an image from a model. The model is created successfully with the image but when I try to render it in template/home.html it doesn't show up for some reason can anybody please help me with this I would really appreciate it! models/Post.py import uuid from django.db import models from django.contrib.auth.models import User # Create your models here. class Post(models.Model): title = models.CharField(max_length=255) image = models.ImageField(upload_to='images') body = models.TextField() owner = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name="posts") createdAt = models.DateField(auto_now_add=True) updatedAt = models.DateField(auto_now=True) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Meta: ordering = ['-createdAt', '-updatedAt'] def __str__(self): return str(self.title) views.py from django.views import generic from base.models import Post # Create your views here. class HomeView(generic.ListView): model = Post template_name = 'home.html' templates/home.html {% load static %} <h1>Posts</h1> {% for post in object_list %} <p>{{post.title}}</p> <img src={{post.image}} alt="Image"> <p>{{post.description}}</p> {% endfor %} settings.py ... ... ... # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = 'static/' # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Base url to serve media files MEDIA_URL = '/media/' # Path where media is stored MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') STATIC_URL = '/static/' I do not know what is happening … -
Caching at QuerySet level in Django
I'm trying to get a queryset from the cache, but am unsure if this even has a point. I have the following method inside a custom queryset: def queryset_from_cache(self, key: str=None, timeout: int=60): # Generate a key based on the query. if key is None: key = self.__generate_key # () # If the cache has the key, return the cached object. cached_object = cache.get(key, None) # If the cache doesn't have the key, set the cache, and then return the cached object. if cached_object is None: cache.set(key, self, timeout=timeout) return cached_object The usage is basically to append it to a function, for example: queryset = MyModel.objects.filter(name__in=["Jane","John"]).queryset_from_cache() Finally, my question: Would usage like this work? Or would it try to hit the database no matter what? -
Google Kubernetes Engine The node was low on resource: ephemeral-storage. which exceeds its request of 0
I have a GKE cluster where I create jobs through django, it runs my c++ code images and the builds are triggered through github. It was working just fine up until now. However I have recently pushed a new commit to github (It was a really small change, like three-four lines of basic operations) and it built an image as usual. But this time, it said Pod errors: BackoffLimitExceeded, Error with exit code 137 when trying to create the job through my simple job, and the job is not completed. I did some digging into the problem and through runnig kubectl describe POD_NAME I got this output from a failed pod: Conditions: Type Status Initialized True Ready False ContainersReady False PodScheduled True Volumes: kube-api-access-nqgnl: Type: Projected (a volume that contains injected data from multiple sources) TokenExpirationSeconds: 3607 ConfigMapName: kube-root-ca.crt ConfigMapOptional: <nil> DownwardAPI: true QoS Class: BestEffort Node-Selectors: <none> Tolerations: node.kubernetes.io/not-ready:NoExecute op=Exists for 300s node.kubernetes.io/unreachable:NoExecute op=Exists for 300s Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 7m32s default-scheduler Successfully assigned default/xvb8zfzrhhmz-jk9vf to gke-cluster-1-default-pool-ee7e99bb-xzhk Normal Pulling 7m7s kubelet Pulling image "gcr.io/videoo3-360019/github.com/videoo-io/videoo-render:latest" Normal Pulled 4m1s kubelet Successfully pulled image "gcr.io/videoo3-360019/github.com/videoo-io/videoo-render:latest" in 3m6.343917225s Normal Created 4m1s kubelet Created container … -
Fat`s formula on python
I have a formula: %fat=495/(1.29579-0.35004(log(hips+waist-neck))+0.22100(log(growth)))-450 How did this fat formula on python? I make it: from math import log fat = 495 / (1.29579 - 0.35004 * log(self.hips + self.waist - self.neck) + 0.22100 * log(self.user.profile.growth)) - 450 But the meanings are far from the truth. Link on calculator https://www.scientificpsychic.com/fitness/diet-calculator-ru.html -
If your program executing second.py file. How would you access variable with data of second.py file? [duplicate]
I've seen many post regarding this but doesn't found solution. You have first.py def AI_click(self): string="" os.system('python second.py') self.lineEdit.setText(string) If this method called, second.py will execute. In second.py you have, string="mntk" How will you use second.py string in first.py function? I also asked here This is nothing to do with import because in real second.py contain AI model and it predicts alphabets using ocr and store string value in variable. That's what I want to access in first.py -
Django mapping urls to views
ModuleNotFoundError: No module named 'playground/urls' I am going through the ultimate django series by mosh hamedani and i came across a problem. I did exactly as he did and it didn't work for me. Here are my urls.py and installed apps. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.staticfiles', 'playground' ] playground/urls.py from django.urls import path from . import views #URLConf urlpatterns = [ path('hello/', views.say_hello) ] storefront/urls.py """storefront URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('playground/', include('playground/urls')) ] -
get the related records in a serializer - django
I am trying to obtain in a query the data of a client and the contacts he has registered I tried to do it in the following way but it did not work. class ClientReadOnlySerializer(serializers.ModelSerializer): clientcontacts = ClientContactSerializer(many=True, read_only=True) class Meta: model = Client fields = "__all__" Is there any way to make this relationship nested? these are my models clients model # Relations from apps.misc.models import City, TypeIdentity, TypeCLient, CIIU from apps.clients.api.models.broker.index import Broker from apps.authentication.models import User class Client(models.Model): id = models.CharField(max_length=255, unique=True,primary_key=True, editable=False) type_client = models.ForeignKey(TypeCLient, on_delete=models.CASCADE, blank=True) type_identity = models.ForeignKey(TypeIdentity, on_delete=models.CASCADE, blank=True) document_number = models.CharField(max_length=255, blank=True, unique=True) first_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) social_reason = models.CharField(max_length=255, blank=True, null=True) city = models.ForeignKey(City, on_delete=models.CASCADE, blank=True) address = models.CharField(max_length=255, blank=True) email = models.CharField(max_length=255, blank=True, unique=True) phone_number = models.CharField(max_length=255, blank=True, unique=True) ciiu = models.ForeignKey(CIIU, on_delete=models.CASCADE, blank=True) broker = models.ForeignKey(Broker, on_delete=models.CASCADE, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) income = models.SmallIntegerField(blank=True, default=0) state = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(null=True, default=None) client contacts model # Relations from apps.clients.api.models.index import Client class ClientContact(models.Model): id = models.CharField(max_length=255, primary_key=True, unique=True, editable=False) client = models.ForeignKey(Client, on_delete=models.CASCADE) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) phone_number = models.CharField(max_length=255) state = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) … -
drf: serializers.ModelField > How can i get user_id appropriately?
I want to implement the 'user_id' to be automatically saved at the backend without receiving it from the client. (when create object!) This is my code. models.py class User(AbstractUser): username = None email = models.EmailField(max_length=255, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() social_profile = models.URLField(null=True,blank=True) realname = models.CharField(max_length=50, blank=True) nickname = models.CharField(max_length=50, null=True, unique=True) address = models.CharField(max_length=200, blank=True) phone = models.CharField(max_length=100, blank=True) def __str__(self): return self.email class Item(models.Model): user_id = models.ForeignKey(User, related_name='item_sets', on_delete=models.CASCADE) category_id = models.ForeignKey(Category, related_name='item_sets', on_delete=models.DO_NOTHING) description = models.TextField() feature = models.TextField() product_defect = models.TextField() size = models.CharField(max_length=6) height = models.DecimalField(max_digits=4, decimal_places=1, default=0) weight = models.DecimalField(max_digits=4, decimal_places=1, default=0) condition = models.CharField(max_length=20) price = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) sold_out = models.BooleanField(default=False) def __str__(self): return self.description view.py class ItemViewSet(ModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer filter_backends = [SearchFilter, OrderingFilter] search_fields = ['description'] # ?search= ordering_fields = ['created_at'] # ?ordering= ordering = ['-created_at'] authentication_classes = (JWTCookieAuthentication,) # create def create(self, request, *args, **kwargs): city = request.data['city'] gu = request.data['gu'] dong = request.data['dong'] if city is not None and gu is not None and dong is not None: location = Location.objects.get( Q(city=city) & Q(gu=gu) & Q(dong=dong) ) else: return Response( {"message": "주소정보를 모두 입력해주세요."}, status=status.HTTP_400_BAD_REQUEST ) … -
Django - Unexpected behaviour with default ordering after annotations
I've discovered a rather odd case where if I set default ordering on a model to id or -id then add distinct annotations to the query, the default ordering is ignored and instead orders by id ascending regardless of what it is set as in the model Meta. However, when I choose a field that isn't specifically id as the default ordering of the model and do the same thing, the queryset is ordered correctly. It only seems to by id. What gives? I'm not sure if this is Django weirdness or postgres weirdness, is it because it's the primary key? If I use .order_by('-id') afterwards it orders as desired and if the ordering gets broken by annotating it, how come it doesn't always break? Example Django version: 4.1 Postgres version: 13.4 class OrderQuerySet(models.QuerySet): def annotateItemCounts(self): return self.annotate( num_items=Count('order_items', distinct=True), num_items_draft=Count('order_items', distinct=True, filter=Q(order_items__state=OrderItem.OrderItemState.DRAFT)), num_items_back_order=Count('order_items', distinct=True, filter=Q(order_items__state=OrderItem.OrderItemState.BACK_ORDER)), num_items_confirmed=Count('order_items', distinct=True, filter=Q(order_items__state=OrderItem.OrderItemState.CONFIRMED)), num_items_in_progress=Count('order_items', distinct=True, filter=Q(order_items__state=OrderItem.OrderItemState.IN_PROGRESS)), num_items_ready=Count('order_items', distinct=True, filter=Q(order_items__state=OrderItem.OrderItemState.READY)), num_items_packed=Count('order_items', distinct=True, filter=Q(order_items__state=OrderItem.OrderItemState.PACKED)), num_items_shipped=Count('order_items', distinct=True, filter=Q(order_items__state=OrderItem.OrderItemState.SHIPPED)), num_items_completed=Count('order_items', distinct=True, filter=Q(order_items__state=OrderItem.OrderItemState.COMPLETE)), ) class OrderManager(models.Manager): def get_queryset(self): return OrderQuerySet(self.model, using=self._db) def annotateItemCounts(self): return self.get_queryset().annotateItemCounts() class Order(models.Model): class Meta: ordering = ['-id'] ... -
Get top rows by one column Django
I'm making a job to categorize earnings and expenses, from app of movimentations. To this, i need get the category to tile, with more cases. For example, in this Scenario: | title | category | count | | ----- | -------------- | ----- | | Pizza | food | 6 | | Pizza | others_expense | 1 | | Pizza | refund | 1 | I want return just the first row, because the title is the same, and category food is used with most frequency. Code example I want get the result using just Django ORM, because i have diferent databases and is more fast than iterate over a large list. Model: class Movimentation(models.Model): title = models.CharField(max_length=50) value = models.FloatField() category = models.CharField(max_length=50) Consult: My actual consult in Django ORM is. Movimentation.objects \ .values('title', 'category') \ .annotate(count=Count('*')).order_by('title', '-count') Result: [ {'title': 'Pizza', 'category': 'food', 'count': 6}, {'title': 'Pizza', 'category': 'others_expense', 'count': 1}, {'title': 'Pizza', 'category': 'refund', 'count': 1}, {'title': 'Hamburguer', 'category': 'food', 'count': 1}, {'title': 'Clothing', 'category': 'personal', 'count': 18}, {'title': 'Clothing', 'category': 'home', 'count': 15}, {'title': 'Clothing', 'category': 'others_expense', 'count': 1} ] Expected result: In this case, i get just one row by title, with the most used …