django-orm

Per-transaction isolation level in Django ORM

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-30 17:23:46
Is it possible to set isolation level for custom transaction (but not with raw sql)? For example, something like: with transaction.commit_on_success(isolation='SERIALIZABLE'): bla As far as I know, there's no way to temporarily change the transaction isolation level in Django for an existing database connection(s). However, you could setup another database connection(s) that mirrors your default database connection(s) but sets the transaction isolation level. e.g. in your settings.py: DATABASES = { 'default': { 'NAME': 'app_data', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'postgres

Django making a list of a field grouping by another field in model

筅森魡賤 提交于 2019-11-30 14:14:13
问题 I have a model called MyModel which has some dummy data as follows: item date value ------------------------------ ab 8/10/12 124 ab 7/10/12 433 ab 6/10/12 99 abc 8/10/12 23 abc 7/10/12 80 I would like to query this Model in such a way that i get an output as follows: [{'item': 'ab', 'values': [ 124, 433, 99]}, {'item': 'abc', 'values': [ 23, 80]}] How would i be able to do this using the django ORM? 回答1: (Apr 4 '16) UPDATE: This is a working solution for Django <= 1.7. For newer versions

Updating selection of objects, each with a different value in bulk (Django)

爱⌒轻易说出口 提交于 2019-11-30 12:13:53
Imagine I have a python dictionary where keys are existing user ids, and values are scores to be added to those users' existing scores. For example: {1: 1580, 4: 540, 2: 678} (this could stretch to n k,v pairs) I need to update the scores of all these user objects (updated_score = original_score + new_score). One way to do it is iteratively, like so: from django.db.models import F scores = {1: 1580, 4: 540, 2: 678} for user_id,score_to_add in scores.iteritems(): UserProfile.objects.filter(user_id=user_id).update(score=F('score')+score_to_add) But that's multiple DB calls. Can I do it in a

Django making a list of a field grouping by another field in model

坚强是说给别人听的谎言 提交于 2019-11-30 09:34:28
I have a model called MyModel which has some dummy data as follows: item date value ------------------------------ ab 8/10/12 124 ab 7/10/12 433 ab 6/10/12 99 abc 8/10/12 23 abc 7/10/12 80 I would like to query this Model in such a way that i get an output as follows: [{'item': 'ab', 'values': [ 124, 433, 99]}, {'item': 'abc', 'values': [ 23, 80]}] How would i be able to do this using the django ORM? (Apr 4 '16) UPDATE: This is a working solution for Django <= 1.7. For newer versions please read Creating your own Aggregate Functions from the docs. Using a custom Concat aggregate taken from

What is the replacement for DateModifierNode in new versions of Django

早过忘川 提交于 2019-11-30 08:50:32
问题 I want to do a query based on two fields of a model, a date, offset by an int, used as a timedelta model.objects.filter(last_date__gte=datetime.now()-timedelta(days=F('interval'))) is a no-go, as a F() expression cannot be passed into a timedelta A little digging, and I discovered DateModifierNode - though it seems it was removed in this commit: https://github.com/django/django/commit/cbb5cdd155668ba771cad6b975676d3b20fed37b (from this now-outdated SO question Django: Using F arguments in

Django and Aggregate: Sum of distinct values?

十年热恋 提交于 2019-11-30 08:47:06
I am trying to do a django aggregate function, but am unable to produce the desired result. What I've got: income_posts.values_list('category__name','amount') [(u'Donation', Decimal("2000.00")), (u'Paycheck', Decimal("1200.00")), (u'Donation', Decimal("1000.00"))] Desired result: [(u'Donation', Decimal("3000.00")), (u'Paycheck', Decimal("1200.00))] I need to Sum the 'amount' fields that have the same category__name. Jordan Reiter From this answer for a related question : from django.db.models import Sum income_posts.values('category__name').order_by('category__name').annotate(total=Sum('amount

Django ORM - objects.filter() vs. objects.all().filter() - which one is preferred?

旧城冷巷雨未停 提交于 2019-11-30 07:51:23
Very often I see constructs like MyModel.objects.all().filter(...) which will return a QuerySet of the default Mananger. At first all() seems to be quite redundant, because MyMode.objects.filter(...) delivers the same result. However, this seems to be safe for the default Manager only, because of the following two statements in the Django documentation: Excerpt from the Chapter "Adding extra manager methods" A custom Manager method can return anything you want. It doesn’t have to return a QuerySet. Definition of the all() manager method: all() Returns a copy of the current QuerySet (or

Model in sub-directory via app_label?

 ̄綄美尐妖づ 提交于 2019-11-30 06:43:27
In order to place my models in sub-folders I tried to use the app_label Meta field as described here . My directory structure looks like this: project apps foo models __init__.py bar_model.py In bar_model.py I define my Model like this: from django.db import models class SomeModel(models.Model): field = models.TextField() class Meta: app_label = "foo" I can successfully import the model like so: from apps.foo.models.bar_model import SomeModel However, running: ./manage.py syncdb does not create the table for the model. In verbose mode I do see, however, that the app "foo" is properly

Django update table using data from another table

☆樱花仙子☆ 提交于 2019-11-30 06:27:17
I have 2 tables products and catagories connected by foreign key. I need to update field products.new_cost using field catagories.price_markup as following: UPDATE products p INNER JOIN categories c ON p.category_id = c.id SET p.new_cost = ROUND(p.pleer_cost * (1 + c.price_markup/100), -1) WHERE p.update = 1 In SQL it's so easy, but how to do it using Django ORM? My simplified try doesn't work Cannot resolve keyword 'category.price_markup' into field. : Product.actived.select_related('category').filter(update=1)).update(new_cost=F('pleer_cost') * F('category.price_markup')) You cannot use F,

Django bulk update with string replace

旧时模样 提交于 2019-11-30 04:52:56
I am trying to update and modify a string field Django's ORM. The equivalent SQL to do this is: UPDATE example_table SET string_field = REPLACE(string_field, 'old text', 'new text'); With that query, I expect old text and old text more text to be replaced with new text and new text more text respectively, for all the entries in the string_field column. Bulk update() seems promising, but doesn't allow me to modify only part of the field, and F() expressions only implement numeric changes, not string replace. I also looked at using raw queries to run the above SQL, but that seems like a sideways