Questions tagged [django-orm]
Django's ORM system, comprising its queryset and model systems.
4,004
questions
0
votes
0
answers
21
views
Django dumpdata to dump all tables without data
I have been using dumpdata in Django for a while. The fact is that dumpdata dumps all of the data including table details. Now, I have a requirement to dump all the tables without even including the ...
0
votes
0
answers
29
views
Django query hangs on a model with a ManyToManyField to "self", when adding to prefetch_related
I have an Offer model with a self-referential ManyToManyField:
class Offer(models.Model):
title = models.CharField(max_length=255)
priority = models.PositiveIntegerField(default=100, help_text=...
0
votes
1
answer
38
views
In Django ORM, wildcard \b does not work (Postgres database) [duplicate]
All other wildcards work correctly but for example when I want to use "\bsome\b" pattern, it can't find any result however, there are many rows in the database that have a word "some&...
0
votes
1
answer
11
views
Django JSONField filter on complex JSON document with list of object
I work with Django 3.2 and MariaDB.
I have an Product Model with an product_settings field (typed as JSONField ).
With a queryset I want to retrieve all products with a type of deposit equals to ...
0
votes
0
answers
29
views
Store foreign key as eccrypted and fetch be decrypt
I am implementing a user management system using django ORM. It is said to store the Password in a different table named "user_password" and encrypt the the foreign key "id" of &...
0
votes
0
answers
22
views
Filtering by distance without using postgis in django-filter
I've checked some answers related to my question but couldn't find solution.
I have Foo and related FooAddress models. In django-filter I cannot filter Foo by distance, tried many options but no ...
1
vote
0
answers
38
views
Integrating Databricks SQL Connector with Django ORM for CRUD Operations
I am working on a Django project that requires integration with Databricks, and I am currently exploring the use of the databricks-sql-connector Python package for connectivity. However, my concern is ...
1
vote
2
answers
52
views
django orm optimize the query
I need query in django orm to clubs list endpoint. with clubs where user is the club owner, or user is Tournament Referee (with empty end_date, or the end_date is more recent than now).
I have models:
...
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 ...
1
vote
1
answer
32
views
How to get unique data for each column from the database in one query (Django ORM)?
I need to get UNIQUE data from EACH column
I have a list of fields:
MY_FIELDS = ['id', 'created', 'And_more_28']
My HORRIBLY INEFFECTIVE code that produces the correct result
qs = Sheets.objects.all()...
2
votes
1
answer
30
views
Make inner joins by using Q objects in Django
I'm customizing a model's Admin change list page in my project.
This model contains a Many to Many field and I want to allow multi-selection filtering.
I've used the Django Admin Multi Select Filter ...
1
vote
1
answer
33
views
APIView Query Not Returning Any Results
I am having one of those days where the things I think are going to be easy on this project are just not turning out that way. I feel like I must be overlooking something very simple here in my ...
0
votes
0
answers
51
views
Unknown output_field type in Subquery in Django
I have the following models:
class Parent1(models.Model):
name = models.CharField(max_length=255)
class Parent2(models.Model):
parent1 = models.ForeignKey(Parent1)
label = models....
-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
0
answers
21
views
How to Perform Unit Conversion before Aggregating Model Fields in Django?
I have a Django model as follows:
class WeightUnit:
KILOGRAM = "kg"
TONNE = "tonne"
LBS = "lbs"
CHOICES = [
(KILOGRAM, _("kg")),
...
0
votes
1
answer
21
views
Is there a way to dynamically select schema to execute SQL queries in Django?
I have a Django app which have a model that stores SQL queries that should be executed on another one of the multiple databases.
There is also a column called schema in that model which is used to ...
1
vote
1
answer
57
views
Django ORM get record with latest date
This is the data I have:
class RdpUserPasswordHash(models.Model):
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='password_hash')
when = models.DateTimeField(...
1
vote
1
answer
28
views
Django Query input results of one queryset to find an object that doesn't appear in another model
Good afternoon,
I am trying to write an DRF endpoint that returns the next unused hint.
I have two models:
class GameActivity(models.Model):
activity_datetime = models.DateTimeField(default=...
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 ...
0
votes
0
answers
35
views
Why Django Count on M2M Field returns wrong value?
I have a manager that calculates all acquired skills by counting sessions related to educational materials attached to a specific skill. Here are my models and manager:
class Trajectory(...
1
vote
1
answer
34
views
Django ORM group by on primary key mysql
In the django ORM it's easy to group by when using an aggregate function like this:
from django.contrib.auth.models import User
User.objects.values('id').annotate(Count('id'))
However if I want to ...
0
votes
1
answer
82
views
why can't django return a plain text response with a link to download the file?
I have in Django eksport functionality, in the custom admin.
So, when requesting to get everything from the database, I make an ORM query of the necessary sample - the query is heavy, but it works ...
0
votes
1
answer
34
views
Group Symbols Together during order_by
When using order_by in the Django ORM it seems that it is ignoring symbol characters in the text when sorting.
For example with the folowing query set.
+--------+
| name |
+--------+
| 'A' |
| '@...
0
votes
2
answers
34
views
Django how to make dinamycally OR queries with ORM
Here is my SQL Query
all_or_conditions = []
if request.GET.get('filter_phone'):
all_or_conditions.append("phone='"+request.GET.get('filter_phone')+"'")
if request.GET.get('...
0
votes
0
answers
16
views
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('...
0
votes
0
answers
51
views
How to populate Django Quill Field from ORM
I am trying to save an object with a Quill Field in django via the ORM. I am using the django-quill-editor module from PyPI
Here is the model:
from django_quill.fields import QuillField
class Product(...
0
votes
1
answer
24
views
Simple Example of Multiple ManyToMany Model Relations in Django
I'm writing a workout app and have a number of models that need to link together. Specifically, I have an Exercise model that needs to track the name of each exercise as well as the primary and ...
-1
votes
1
answer
66
views
How to do a bulk delete under condition in Django
There are several questions similar to mine but none are satisfactory. Some questions deal with the management of duplicates under conditions, others in the context of a database having a large number ...
1
vote
2
answers
64
views
Django self.model.DoesNotExist
I have a user with a field set as None:
None|Default User|07/07/2023
However, Django for some reason does not see it:
queryset=Q(id=UUID(User.objects.get(user_id=None)
...
raise self.model....
0
votes
0
answers
26
views
How to differentiate created objects and updated objects in Django bulk_create?
I am using bulk_create to create objects in one query. I set update_conflicts to True to update permission level if the record already exists. bulk_create returns the
created and updated objects. How ...
0
votes
1
answer
29
views
How can I see the values of a ManyToMany field based on a Foreign key value in Django Admin Panel?
I am making a Django app for multiple choice question-answer exam. I have created a Subject, Question and Exam model as below.
class Subject(models.Model):
subject_name = models.CharField(...
0
votes
2
answers
45
views
How can I change this model for multiple choice answer?
I am making a Django app for multiple choice question-answer exam. I have created a Question model as below.
class Question(models.Model):
subject = models.ForeignKey(Subject, on_delete=...
0
votes
2
answers
54
views
Can a Django query filter with a relationship reference a parent's field value?
I have a Training and TrainingAssignment table in my django app. Users sign into the app and complete a Training which creates a TrainingAssignment record. The Training table has a field, days_valid ...
0
votes
0
answers
59
views
Non atomic transaction inside transaction.atomic() block in Django
I would like to insert in db some objects directly inside transaction.atomic() block, not waiting that block finish.
Why do I need this?
I need atomic block because of a business logic and without it, ...
0
votes
2
answers
40
views
Cannot resolve keyword '-name' into field. Choices are: name, account, account_id
Why am I getting this error and is there any alternative way to achieve the result of the below query?
Cannot resolve keyword '-name' into field. Choices are: name, account, account_id.
self.queryset =...
1
vote
1
answer
64
views
Django - Annotate count of related objects
Let's assume the next models:
class A:
b=models.ForeignKey("B")
class B:
pass
I want to annotate queryset of B count of related A objects
def annotate_count_a(b_queryset):
/* .....
0
votes
0
answers
50
views
How to optimize Django view for performance?
I am wondering what the best practices are for optimizing view performance.
I have this view that takes over 90 seconds to load (with 5 queries, 2 of which take the bulk of time). It has some complex ...
0
votes
2
answers
52
views
Django- filtering on ManyToMany field with exact matches
I have the following models:
class Hashtag(models.Model):
title = models.CharField(...)
class Annotation(models.Model):
...
hashtags = models.ManyToManyField(Hashtag)
I want to get the ...
0
votes
1
answer
39
views
Django annotation across multiple models
I am looking to annotate to each BonusCustomer the Sum of billable_amount from the load table.
class BonusCustomer(models.Model):
customer = models.CharField(max_length=150, blank=True, null=True)
...
1
vote
1
answer
52
views
Django: SUM of COUNT in annotations
I have the following simple models:
class Member(models.Model):
name = models.CharField(max_length=100)
class Booking(models.Model):
date = models.DateField(default=now)
price = models....
1
vote
1
answer
47
views
Creating and saving a model object with a calculated m2m field Django
New to Django, I don't know if it's still worth it. I'm currently trying to save a model form with a many-to-many field that should be set randomly according to other fields(category, subcategory, ...
1
vote
1
answer
35
views
Intersection of QuerySet and list of objects
Assume that I have a query set of Product model.
products_qs = Product.objects.filter(...)
products_list = [<Product 1>, <Product 5>]
How can I detect intersection of products_qs and ...
1
vote
1
answer
29
views
Django ORM for custom python function
I have following two models
class Membership(models.BaseModel):
user = models.ForeignKey(User)
package = models.ForeignKey(Package, on_delete=models.PROTECT, blank=True, null=True, ...
1
vote
1
answer
27
views
Django Multi OR Operations
I am trying to do an OR operation for a specific group without knowing the number for each so that it is more than an OR LIKE
SELECT * FROM movies WHERE genres LIKE '%Action%' or genres LIKE '%Comedy%'...
0
votes
0
answers
17
views
Read data from dynamic table Django
I have automated batch process which creates tables in SQLite DB and update the new created table name in one of the tables defined by Django ORM.
I would like to know how can I use Django ORM to ...
0
votes
0
answers
14
views
bulk_create() and save() methods django
I am using the bulk_create method to save multiple objects at once. But I have an overridden save() method and it is not called in this case. And I don't want to spam extra queries.
Maybe there is ...
0
votes
1
answer
59
views
Add a set of 'sub-forms' (probably form set) to a ModelForm
I'm making some progress in solving this. What I want to model is this:
I have a model for materials, a model for projects, and an intermediary model to specify more data to the many-to-many ...
0
votes
1
answer
39
views
Django ORM .distinct() seems to return duplicate results
I have an Event model that represents an Event happening. I have another EventShow model which represents a date and time that the event is taking place. Each event can have multiple shows, so I have ...
0
votes
0
answers
20
views
Django SearchFilter exists relationship without DISTINCT
Table search is implemented through rest_framework.filters SearchFilter with the addition of DISTINCT, which is not suitable for a large database, how to avoid this, what are the hacks for this
class ...
0
votes
1
answer
95
views
Django ORM query taking very long but Raw query runs as expected
I have a simple get query
key = TenantKey.objects.get(pk=api_key)
When I'm running a load test, for many requests the above query is taking multiple seconds (max 15s) which is very strange. So I ran ...