Questions tagged [django-orm]

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
1

votes
1

answer
34

Views

Django complex query through builder

I have not been able to make a complex query using ORM for some time. I know that this is possible, so I will forgive help. class Game(models.Model): no matter class Competition(models.Model): game = models.ForeignKey(to='game.Game', verbose_name=_('game'), related_name='competitions', on_delete=mod...
Andrei Tupic
1

votes
1

answer
32

Views

Count a Count with Django Aggregation through multiple Many to Many fields

Given a Django model with two M2M fields: class Book(models.Model): name = models.CharField(max_length=300) authors = models.ManyToManyField(Author) publishers = models.ManyToManyField(Publisher) And starting from a queryset of Authors: authors = Author.objects.filter(...) How can I annotate a count...
43Tesseracts
1

votes
1

answer
34

Views

Join unrelated models and delete duplicate from the queryset

I really need help here. I have the two tables below. As you can see they are completely independent (No relationship between the two). class People(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=35) phone_number = models.CharField(null=True, bla...
Curtis Banks
1

votes
1

answer
34

Views

Django: Annotate value based on related set

I'm looking for a way to annotate value of aggregated filtered related set. class Location(... ... class Ticket(... location = ForeignKey(Location...) date = ... price = ... I need to annotate maximal price of ticket in a daterange. So if I set only last 30 days, it returns me all Location objects...
Milano
1

votes
0

answer
41

Views

Postgres query to Django ORM

I want to do this query bellow in django orm, i've tried to do with the queryset example and it doesn't work, always returns the error, i want to know if is possible to solve this. I think the problem migth be GROUP BY, and the Django ORM doens't do the GROUP BY, but this it is just a guess. error:...
Daniel Pereira
1

votes
1

answer
21

Views

Unnecessary join in django queryset of model with many-to-many field and intermediate table

When I try to get all objects of my model FabricCategory, it returns some duplicates. I've found unnecessary LEFT OUTER JOIN in sql query: python manage.py shell_plus --print-sql >>> FabricCategory.objects.all() SELECT `product_fabriccategory`.`id`, `product_fabriccategory`.`price_impact`, `product_...
s.weszler
1

votes
1

answer
13

Views

django access related model status in custom managers

I use model_utils library in Django. I've got two models as shown below class Book(TimeStampedModel): STATUS_CHOICES = Choices( (0, 'public', _('public')), (1, 'private', _('private')), ) status = models.IntegerField( verbose_name=_('status'), choices=STATUS_CHOICES, default=STATUS_CHOICES.public, d...
nasiajai
1

votes
1

answer
25

Views

Django get count of object many to many field in a set

I can't seem to wrap my head around mildly complicated queries in django. I have a player that has played games. each play has a many to many field with players that played that game. With player1, how do i calculate which opponent he has played the most with django orm? In SQL I guess this could be...
hvgab

View additional questions