Questions tagged [django-queryset]
Django querysets are the primary abstraction for retrieving objects from Django's ORM system
6,823
questions
1
vote
1
answer
32
views
Annotate Django Foreign Key model instance
Is it possible in Django to annotate a Foreign Key instance?
Suppose I have the following models:
class BaseModel(models.Model):
pass
class Foo(models.Model):
base_model = models.ForeignKey('...
0
votes
1
answer
43
views
Is it possible to annotate a column which contains a queryset?
I want to show a table on a HTML template with data from GroupCaseFile model. But one of the columns must contain data from the most recent ProceduralAct object, specifically: 'act_number', 'act_type',...
0
votes
0
answers
20
views
I have a problem with annotate. I want to add a subset counter column, but it doesn't get added
class ProductGroupInstanceInlineAdmin(admin.TabularInline):
model=ProductGroup
@admin.register(ProductGroup)
class ProductGroupAdmin(admin.ModelAdmin):
list_display=('group_title','is_active'...
0
votes
1
answer
26
views
How can I filter an annotated query set
I have the code below that returns an aggregate of authors that have a book and the total amount of authors. This works well, but I want to get the count of authors that have a particular type of book ...
2
votes
1
answer
73
views
Django (DRF) ORM - Simple left join with reverse relation
I am trying to select data from my postgreSQL database using Django 3.2.9 and DRF 3.12.4.
Here are my models :
class Headpiece(ValidatedModelbase):
class Types(models.TextChoices):
POWDER =...
2
votes
0
answers
66
views
+50
Recursive Query with Django-CTE
I have a Tree model that i need to prefetch all the childs and user of the comments all at once:
class AnalysisComment(MPTTModel, TimeStampMixin):
parent = TreeForeignKey(
"self",...
0
votes
1
answer
102
views
django render multiple templates with same context hitting db every time
I am working on showing multiple tables in multiple tabs using htmx for lazy-load. The code is working properly, but I couldn't solve two things.
The queryset is hitting db 4 times.
I was trying to ...
0
votes
1
answer
24
views
Django query with Q filter _lte on DateField (USE_TZ=True) doesn't work (MySql DB)
I got an Invoice model with a field created_at as models.DateTimeField() with a few records containing several dates:
With an HTML form, I want to filter by dates
<input name="start" ...
2
votes
2
answers
45
views
Order Django queryset by value closest to 0
I have a queryset that is returning a list of entries that are tied for the lead in a contest...
leaders = ContestEntry.objects.filter(name=game, wins=wins)
After I get this data I need to put ...
1
vote
1
answer
51
views
How to order a Django queryset by two separate columns
I have a ‘Entry’ model with two columns, ‘wins’ and ‘points’.
Right now I am ordering them by wins but when there are two people with the same amount of wins I would like to fall back on points as a ...
0
votes
1
answer
41
views
Django queryset length is 1 but doing .first() and .last() return two different objects
Encountered unusual behaviour django ORM query. Filtered queryset when printed displays only one value but when i tried doing .first() and .last() on that queryset it displayed two different values
In ...
0
votes
0
answers
24
views
Django queryset.filter issue with model type pgfields.ArrayField(models.DateField())
I'm trying to filter a queryset by a date range, on the model it is pgfields.ArrayField(models.DateField()) it is stored in the actual table as text[] (ide). This is the specific piece of code that ...
2
votes
1
answer
28
views
Django ORM ForeignKey queryset output using annotations
I have the following 3 django models (using some abstractions):
class Person(models.Model):
full_name = models.CharField(max_length=120, validators=[MinLengthValidator(2)])
birth_date = models....
0
votes
0
answers
48
views
Django issue altering get_queryset in Class Based View with POST data
Not really sure how I can't figure this out but I am trying to POST a form to alter the contents of get_queryset() but it isn't keeping the filtered items, it calls get_queryset multiple times during ...
1
vote
1
answer
35
views
Combining two Queryset for sorting , Django [closed]
I have two Queryset result. I need to combine before it gets sorted. How to solve this problem in Django? And it should convert it back to Queryset for sending it to template.
Tried to convert it to a ...
-1
votes
0
answers
25
views
aggregate on annotate inside subquery
return queryset.annotate(
sum_amount=Subquery(
RI.objects.filter(r_queryset=OuterRef('pk'))
.annotate(
sum_amount=Sum(
...
0
votes
1
answer
36
views
How to get specific values in Django UpdateView?
I have a generic UpdateView where the leaders can manage the settings of the users whom connected to the leaders's company.
I like to have only that values in the select field where the company_id is ...
0
votes
0
answers
38
views
How can Django QuerySet filters modify the fields for comparison? (Like inet6_aton for IP addresses.)
Take this MySQL database for example, which stores IP addresses as strings in either IPv4 or IPv6 format.
name | ip
------+---------------------------------------
Tony | 127.0.0.1
Jones | 2001:db8:...
0
votes
1
answer
38
views
How can I achieve filtering with multiple values for the same parameter in Django?
I am building a Django website that displays snowboards that will fit you based on some parameters.
One of the parameters is gender and for example if the user specifies she is a girl, then I want to ...
0
votes
1
answer
25
views
Querying Django Models linked by a Foreign Key to get a complete Query set, counting liked posts
This is a CS50 Pset - Network - I'm battling my way through this and all but this bit is finished
I think I have trapped myself into a corner, I have 4 different Models, 3 are related to this question,...
0
votes
0
answers
29
views
I want to filter a queryset according to which button is pressed
i am quite new to django. I have a Task model which has various fields such as date, task name, description, is_completed, level of importance. I what to filter the result according to which button ...
0
votes
1
answer
53
views
How to get 1 list when using django queries with a M2M relationship
This question is very similar(if not the same to): Django query — how to get list of dictionaries with M2M relation? .
I am just asking this question to be able to learn if there has been any ...
1
vote
1
answer
61
views
how to pass queryset or kwarg to RangeFilter class in Django filters
I'm working on a Django-driven website which uses django-filters and, specifically, RangeFilter to show price diapason of the real estate properties and visualize it as a slider on search form.
My ...
0
votes
2
answers
36
views
Using Django ORM to query a Model with two FKs that are related through an unique_together constraint on a third Model
I am currently facing a challenge in creating a QuerySet that accurately represents the relationships within my Django models. I have a model equipped with two foreign keys, FK1 and FK2. These two ...
1
vote
3
answers
66
views
How can I order a Django query by a field of a related model?
I have these two models, ChatRoom and ChatMessage, which are related. My goal is to order the ChatRoom queries in a way that the room with the most recent message, as determined by the sent_timestamp, ...
0
votes
2
answers
31
views
Count of records created in each hour interval starting from midnight to present time
I need to retrieve count of records created in each hour duration from midnight to present time. To do so the model contain a created_at timestamp field which will record the created time.
The model ...
1
vote
1
answer
28
views
Django F-expression transform output value
I'm using an F-expression to get a foreign key object's date value. But it returns a datetime object as the date. How can I transform it to 'YYYY-MM-DD' format?
from django.db.models import F
...
0
votes
0
answers
19
views
best practice for dynamic filtering
I want to filter with keywords the user can enter.
for example:
models.py:
class Product(models.Model):
name = models.CharField(max_length=128)
description = models.CharField(max_length=256)
...
1
vote
2
answers
35
views
Order by one of two fields
I have a model that has two character fields, one or both of which may be populated. I'd like to called QuerySet.order_by something like:
qs.alias(name=lambda x: if x.field1 then x.field1 else x....
0
votes
2
answers
33
views
Select * for reverse lookup
I've have three models in Django.
class Product(models.Model):
name = mdoels.CharField()
class ProductCharateristics(models.Model):
name = models.CharField()
description = models.TextField()
...
1
vote
1
answer
44
views
How to filter an item in one queryset from appearing in another queryset in django
I have a Django view where I am getting the first queryset of 'top_posts' by just fetching all the Posts from database and cutting it in the first four. Within the same view, I want to get "...
-1
votes
1
answer
43
views
How can I properly Query data from a django model without [closed]
im trying to create a simple django app for buying and selling shares but im having trouble querying my data properly specifically the amount of available shares.
These are my models:
from django.db ...
0
votes
1
answer
45
views
Django | How to query foreignkey and return only one object on a specific key (prefetch)
I am having a headache writing a query :slight_smile:
That’s my models:
`class Mission(models.Model):
machine = models.ForeignKey(Machine, on_delete=models.CASCADE, related_name="missions&...
0
votes
0
answers
23
views
Django's query set filter with icontains stops working if there isn't at least one regisrty with unempty data at target column, what's the logic?
Okay, so I made a search form with some select fields I use to filter what plant species will appear in the search result page, like only species of a specific family.
How it works: no value selected ...
1
vote
1
answer
28
views
Django filtering bey a child of a child
I have these 3 models Stock, Product and ProductDepartment. I need to filter Stock using ProductDepartment id.
class Stock(models.Model):
product = models.ForeignKey(Product, on_delete=models....
0
votes
0
answers
31
views
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 ...
1
vote
1
answer
56
views
How to Join (NOT COMBINE) two more django querysets?
I’m new to Django framework, may be this problem seem to be fun to some experienced developers here.
So, I have a django model:
STATUS_CHOICES = (
(‘CL’, ‘CLOSED’),
(‘FR’, ‘FORWARDED’),
(‘...
1
vote
1
answer
45
views
Query child objects through parent model - Django
Is it possible to query all child objects through parent model and eventually get the subclass of every element in the queryset.
models.py
class employee(models.model):
first_name=models.CharField(...
-1
votes
1
answer
58
views
How to optimize nested loop query of models with one-to-many relationship
I have two models with a one-to-many relationship. There are several objects of each model class in the database. I created a custom queryset that iterates over all parent objects and all child ...
0
votes
0
answers
29
views
Django left join with filtered relation in QuerySet for ListView
I am a Django/Python novice. I am developing a website to help me manage a small golf society. A major function of the website is to enable members to view and book their place on upcoming events.
The ...
0
votes
1
answer
104
views
django queryset that counts occurrences of sub string in field
I have a model called Animal that contains a field called text that starts with the animal name followed by optional text e.g. cat - grey long hair
class Animal:
text = models.TextField()
...
1
vote
1
answer
29
views
annotate django query by substring
How do you annotate a query set using a substring from a field?
I presume something like this:
query_by_domain = (
queryset
.annotate(domain=Substr("email", F("email")....
0
votes
1
answer
25
views
Summarize Django Queryset where Amount falls into Specific Groups
I'd like to group my transactions by the amount category that they fall into and sum those. I'd love to do this with 1 query, but I can't figure out what this kind of grouping is called. So I'm having ...
0
votes
1
answer
30
views
Django get pk row if pk is found in queryset filter
I have the current table example :
I know how to get the rows where the ID is found in :
result_query_1 = models_contacts.objects.filter(company_members_id__icontains= str(pk)+";")
...
2
votes
1
answer
64
views
Order Django queryset by annotated field and annotate it again
I need to order Django queryset by annotated field and then annotate result with row number.
Steps:
Add complex_order field to QuerySet that defines extra logic for future ordering.
Order QuerySet by ...
1
vote
2
answers
21
views
Django filtered and pagination issue
I have a form that filter a queryset, filtering are ok, but if I use pagination links, I loose the filtering value. How can I paginate my filter result ?
template table.html
{% if is_paginated %}
&...
0
votes
2
answers
47
views
Django queryset from url parameter issue
I have multi models, and I want to have one listview to display it.
I would like to have something like this:
model = self.kwargs['name']
queryset = model.objects.all()
but seems not working....
any ...
0
votes
0
answers
46
views
Django ORM takes more time than hitting SQL Server with SqlEngine
I have a django rest application under development. I am trying to follow the best practices while creating it and thus I have included the models and serializers and using those to access the data.
...
0
votes
1
answer
26
views
How to query models with a related model in a onetoone relationship in Django?
Models from the one-to-one Django docs:
from django.db import models
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
def ...
0
votes
1
answer
24
views
Django Queryset counting number of rows based on aggregated field condition
I have following model:
class Purchase(models.Model):
date = models.DateField()
cost = models.IntegerField(null=False)
...
I need to return amount of purchases for each day, with cost ...