Questions tagged [django-orm]

1

votes
2

answer
32

Views

How to filter foreign key objects in django queries?

I have two models, one related to other by foreign key like this class CapturedPrescriptionModel(ColModel): p_id = models.IntegerField() p_age = models.IntegerField() p_gender = models.CharField(max_length=10) p_care_type = models.CharField(max_length=100) bacteria_id = models.ForeignKey(BacteriaLis...
sankycse
1

votes
1

answer
19

Views

Non-binary LIKE in MySQL through Django ORM

This is a follow-up from this question. Although I can write a non-binary LIKE query such as - SELECT COUNT(*) FROM TABLE WHERE MID LIKE 'TEXT%' in raw SQL, I would like to know if it's possible through the Django ORM. Both startswith and contains seem to be using a binary pattern search.
Sidharth Samant
1

votes
0

answer
10

Views

How to group by and aggregate conditional in Django ORM

I have a Django query to get average hours worked per day per employee (There could be multiple worklogs per day). I want to split these up in weekday and weekend work. I have tried the following: qs = Worklog.objects.filter( day__range=[start,end] ).values( 'worker__fullname' ).annotate( weekday=Ca...
Matt
0

votes
0

answer
5

Views

Grouping queryset by column value

I have a queryset that returns Tasks by client id from the following models and would like to get some more filters to receive more precised data. Models are just a example structure of what I am trying to achieve: class Client(models.Model): name = models.CharField(max_length=255) def __str__(self)...
tookas92
1

votes
2

answer
274

Views

django prefetch_related & Prefetch nested

I'm trying to return, for each UserProfile, which has one-to-many Subscription, which has a Foreignkey to both Artist and UserProfile, with each artist having many ReleaseGroup, the count of future release groups that each UserProfile have. In short: I want to return the total count of upcoming rele...
zerohedge
1

votes
1

answer
33

Views

Find models that have only one particular related model

Consider the following models: class Product(models.Model): name = models.CharField(max_length=...) class Size(models.Model): name = models.CharField(max_length=...) products = models.ManyToManyField(Product, through=ProductXSize, related_name='sizes', related_query_name='size') class ProductXSize(m...
x-yuri
1

votes
1

answer
25

Views

How to compare counts in django ORM?

I have model like this: class A(models.Model): done = models.Boolean() And want to check if all done are True: A.objects.count() == A.objects.filter(done=True).count() But how to do the same thing inside DB in one query? ??? A.objects.annotate(Count('done??')).aggregate(??) ???
Aiven
1

votes
1

answer
50

Views

What is the usage of `FilteredRelation()` objects in Django ORM (Django 2.X)?

I've seen Django 2.0 consists of FilteredRelation object in queryset. What is the usage of newly introduced FilteredRelation? What I've looked into? I observed Django 2.0 Documentation but I could not understand idea behind this FilteredRelation object. I looked into following code. But I didn't get...
Devang Padhiyar
1

votes
1

answer
66

Views

Count occurrences of values on a single column grouped by week

I'm trying to accomplish this using Django 2.0 ORM, but if you can solve this with a raw SQL query that would be very helpful too. Say for example I have a table with the column 'destination', which will always be the name of a city, such as 'Los Angeles', 'New York', 'San Francisco', or 'Seattle' (...
Florence
1

votes
1

answer
377

Views

Django Rest Framework - automatically annotate queryset

I use one Serializer in many different places in my project. I need to use one annotation but the problem is that I don't want to annotate it in all views so I would like to do universal annotation in the Serializer itself. It is possible? Now I need to do this before every serialization: City.objec...
Milano
1

votes
1

answer
94

Views

HighCharts Render Annotated Queryset in Jinja2 Template

In my Jinja2 template I want to render a JavaScript array similar to this: [{ name: 'test', data: [ [Date.UTC(1970, 9, 29), 0], [Date.UTC(1970, 10, 9), 0.4], ... ] }, { name: 'Transport', data: [ [Date.UTC(1970, 10, 25), 0], ... ] }] I already managed to build a rather complex queryset in my Django...
Yannic Hamann
1

votes
0

answer
211

Views

How to access one to many relationship after bulk_create in Django

I have a problem with accessing bulk inserted one-to-many relationship objects using bulk_create. Here is my code: My models: class Person(models.Model): # ... other fields class Post(models.Model): person = models.ForeignKey(to=Person, related_name='posts') text = models.CharField(max_length=100) #...
adkl
1

votes
0

answer
35

Views

How to best include field from Django ManyToManyField custom intermediary model when using prefetch_related?

Models: class User(models.Model): teams = models.ManyToManyField('Team', through='TeamMember', related_name='members') class Team(models.Model): pass class TeamMember(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) posi...
offex
1

votes
1

answer
497

Views

How to group by week with Django ORM

I am using the following SQL code to check previous sunday: DATE_ADD(tbl.date, INTERVAL (- 1) * DAYOFWEEK(tbl.date) + 1 DAY) AS week Could you tell me whether I can use the same thanks to django models ? I have completely no idea how to do this. In another words I want to group by sunday in my quer...
python_beg22
1

votes
0

answer
32

Views

Django ORM , Doubts regarding normalization

I have a table in which data gets written in a very fast rate (around 40000 writes per minute) class dummyclass(): field1 = models.CharField() field2 = models.IntegerField() ... field6 = models.DecimalField() There are about 6 to 8 fields in it which is constantly changing So i decided to split thi...
Anoop Ar
1

votes
0

answer
62

Views

inspectdb command crashes when generate model classes from postgres db

when executing inspectdb > modelys.py , i'm getting the following error. I searched for solution but i cant find anything. More over i dont know what this error really mean. (gathiApiVirtualEnv) G:\GathiCatalog\dev\gathiApi\gathi_api>python manage.py inspectdb >models.py Traceback (most recent call...
Newcomer
1

votes
1

answer
308

Views

Django 2.0 - iexact translates to LIKE and not ILIKE

I have a model like this: class Article(models.Model): title = models.CharField(max_length=200) content = models.TextField() class Meta: db_table = 'article' and I write the query: articles = Article.objects.filter(title__iexact='hello world') print(articles.query) The output is: SELECT ... FROM `ar...
NunchakusHuang
1

votes
1

answer
660

Views

Serializing joined tables in serializers rest framework

So i am trying to serialize multiple joined tables with django serializers. I cant find a way to do this. The query being executed is raw sql. The models are as below class UserDetail(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) mobile_number = models.IntegerField() n...
Wendinoda Washaya
1

votes
0

answer
114

Views

Why do django queries to hot standby go slower than queries to master?

I have two servers, running postgres, setup to be master/replicator using hot standby. When I make queries using django on the master server the queries take roughly half the time that the same queries on the replicated server take. The servers are identical except that one is running a read/write...
B.Adler
1

votes
0

answer
33

Views

Change models.AutoField(primary_key=True) to Hexadecimal

I am using django with mongodb using the djongo ORM. I am facing a problem. I want to set id to be the autofield and according to django AutoField is of IntegerField type. But when it is inserted in mongodb, mongodb uses its conventional 12byte hexadecimal value. This is the problem why I cannot edi...
Mr. Blue
1

votes
0

answer
158

Views

Using GROUP_CONCAT with other annotations in Django

I use an annotation which counts upvotes/downvotes while returning a list of articles: queryset = queryset.annotate( upvotes_count=models.Sum( models.Case( models.When(likes__like_state=1, then=1), default=0, output_field=models.IntegerField() ) ) ).annotate( downvotes_count=models.Sum( models.Case(...
Alexey Kislitsin
1

votes
0

answer
58

Views

A Django QuerySet that always returns iterator()

Is it possible to define a custom QuerySet, that will always return the output of .iterator() when it is iterated, while keeping all the other QuerySet functionality? Wrapping an existing QuerySet would work, too. Currently, the only solution I came up with is this awful wrapper class: class Iterato...
lue3Seba
1

votes
0

answer
35

Views

how to apply complicated ORM query in django

I have 3 models. I am using billmanagment for date and customerproductbill table save record of product sale that how many products sale. I am using ORM django query and get record correctly but i need also those product which is not sale and in my customerproduct just save sale product record. I...
zeeshan
1

votes
0

answer
43

Views

Complex query annotation for each distinct

In PurchaseOrder list view I would like to display the total quantity grouped by each distinct unit. I'm using the following models and function but there's a database hit every time get_quantity_by_unit() is called - for each object in the list. class PurchaseOrder(models.Model): lines = models.Man...
bdoubleu
1

votes
1

answer
61

Views

How to count tags with tag name of a user in Django ORM

I have a Post Model like below and I am using django-taggit class Post(models.Model): user = models.ForeignKey(User) post = models.TextField() tags = TaggableManager() >>>p1 = Post(user='user1', post='Some description', tags='python, java, js') >>>p1.save() >>>p2 = Post(user='user2', post='Some desc...
kishore
1

votes
0

answer
71

Views

Django ORM exclude fails

I have some problems with my query - with filter() it's ok but with exclude() doesn't work. My models: class Dictionary(DateTimeModel): base_word = models.ForeignKey(BaseDictionary, related_name=_('dict_words')) word = models.CharField(max_length=64) version = models.ForeignKey(Version) class Freque...
Mike Br
1

votes
0

answer
43

Views

Django: sort by related model with multiple criteria, put nulls last

So this super long query almost works as needed: context['user_artists'] = Artist.objects.filter(users=current_profile) \ .prefetch_related(Prefetch('release_groups', queryset=ReleaseGroup.objects.filter(release_date__isnull=False, release_date__gte=startdate) .order_by('release_date'), to_attr='rgs...
zerohedge
1

votes
0

answer
135

Views

Doing a MySQL REPLACE INTO in Django?

Suppose i have more than 180k user object, and some of them are already present in table, and the table has email Id unique index, So i want to update the existing records and insert the new records, In MySQl i came to know that there is option called REPLACE INTO, Is there any way to run the REPLA...
1

votes
1

answer
45

Views

How to add a sortable column from the admin log in Django

In the Django admin area I need to display when an object was last modified by another user. Therefore I want to leverage Django’s built-in admin log. I came up with this solution: class MyModel(models.Model): ... @property def admin_last_modified(self): from django.contrib.admin.models import Log...
Boldewyn
1

votes
1

answer
299

Views

Self Referencing Symmetrical Many to Many Django Model in Admin or View

How do you get the other side of a symmetrical self reference in a M2M django model? Say we are making a parts catalog, and we have lots of Parts and we want to have an Interchange to show which parts can be used in place of another: class Part(models.Model): name = models.CharField(max_length=300)...
chris Frisina
1

votes
0

answer
44

Views

Counting overlapping days in django

In my django project, I store user's vacation: class VacationRequest(BaseModel): requested_by = models.ForeignKey(User, related_name='vacation', verbose_name='User') start = models.DateField(__('Start')) end = models.DateField(__('End')) I need a feature to generate report. Reports are generated for...
dease
1

votes
0

answer
20

Views

Checking tree modifications in django-treebeard ORM before saving

I want to double-check if I am correctly interpreting the following section of the django-treebeard docs: django-treebeard uses Django raw SQL queries for some write operations, and raw queries don’t update the objects in the ORM since it’s being bypassed. Because of this, if you have a node in...
ZG101
1

votes
0

answer
49

Views

Django ORM Exclusive ORs

I have an issue with my Django ORM query. This query: Ticket.objects.filter( Q(change_personal_data__personal_data__number=number, change_personal_data__is_active=True) ) produces the following query: SELECT 'tickets_ticket'.'id' FROM 'tickets_ticket' INNER JOIN 'tickets_changepersonaldata' ON ('tic...
Kisiel
1

votes
0

answer
70

Views

good way to write thread safe middleware in django

I want apply required filtering for almost all models, all queries in quite big django application. Actually I am looking for a right way to implement a 'query-set driven' middleware (instead of standard 'request-driven middleware') but without manipulate any db driver (no patching, wrapping, etc)....
Sławomir Lenart
1

votes
1

answer
91

Views

Django foreign key constraint with Model that lives in different database

I'm trying to use the oauth2_provider library which provides a model for AccessToken, which foreign keys into a User model. My User model will actually live in a different database from the OAuth2 token models. I can use a router to direct which DB to use for a particular model, but am I correct in...
Nathan
1

votes
0

answer
33

Views

Django query for transactions only where there are multiple transactions for company on the same date

I have a model that consists of company name and transaction date columns. How do I construct a Django query that retrieves only those records for which there are multiple records for that company on the same date? It should exclude any records if there is only one record for that company on that...
William234234
1

votes
1

answer
61

Views

Is there any way to get total count of table row and table data in single Query

The problem is, to get count and table data, I have to hit the database two times in Django. For example: count = queryset.count() # To get count data = queryset.values('columns') # To get data Is there any way to get data in the single query. One solution is to use len() function, but it is not goo...
vermanil
1

votes
3

answer
47

Views

How to make multi filter on django orm?

I have a table with fields: No. | name | utc_date | utc_time | ------------------------------------ 1 | John | 181014 | 140104.12 | 2 | Mark | 181014 | 152312.01 | 3 | Kim | 181015 | 092345.23 | 4 | Jane | 181015 | 234543.32 | How can I create Django ORM query like that: ? (ut...
Bryan Woo
1

votes
0

answer
233

Views

How to convert this RawQuerySet into QuerySet?

EDIT I don't need this to be Django ORM at all, I just need QuerySet instead of RawQuerySet. I'm having a hard time converting SQL query into Django ORM. The point is to reorder QuerySet of Article objects such that every and only every 4th Article has permanent=True. This is the function: def perm...
Milano
1

votes
1

answer
38

Views

Django update all Users field Decimal

from decimal import Decimal from apps.main.models import User from django.db.models import F User.objects.all().update(freeze_balance=F('freeze_balance') + Decimal(F('balance') / 8300)) ERROR -> TypeError: conversion from CombinedExpression to Decimal is not supported How do I write an ORM request...
Dilkhush Vakhabov

View additional questions