Saving an inline view and executing an aggregating function only once

423 views
Skip to first unread message

Victor

unread,
Nov 7, 2013, 4:04:33 AM11/7/13
to django...@googlegroups.com
I made an effort to simplify my app and translate it into English.
Here it is
=================
models.py
.................................
class Items(models.Model):
code = models.CharField(primary_key=True,max_length=15,db_column='code')
description = models.CharField(max_length=255, db_column='Description', db_index=True)
category = models.IntegerField(choices=categoria, db_column='Category',default=2)
total_quantity_in_store=models.IntegerField(db_column='total_quantity_in_store', default=0)
def __unicode__(self):
return self.description
class Meta:
db_table = u'Items'

class Order(models.Model):
id_order = models.IntegerField(primary_key=True,db_column='id_order')
patient = models.ForeignKey(Patients, db_column='patient')
def __unicode__(self):
return u"Ord.%s per %s" % (self.id_order, self.paziente)
class Meta:
db_table = u'Order'

post_save.connect(TotalInStore, sender=Order)

class OrderDetail(models.Model):
id_order = models.ForeignKey(Order,db_column='id_order')
item_code = models.ForeignKey(Items,verbose_name='Items')
quantity = models.IntegerField(db_column='quantity',blank=True,default=0)
class Meta:
db_table = u'OrderDetail'
==================
admin.py
......................
class OrderDetailInline(admin.TabularInline):
model=OrderDetail
raw_id_fields = ['item_code',]
fields=('item_code', 'quantity',)

class OrderOption(admin.ModelAdmin):
readonly_fields = ['order_id', 'patient']
list_display = ( 'patient','order_id')
fields=( 'order_id', 'patient')
inlines=[OrderDetailInline,]

admin.site.register(Order,OrderOption)
....................
=========================
signals.py
def ExecuteQuery(query):
from django.db import connection
cursor=None
cursor= connection.cursor()
cursor.execute(query, [])
return cursor.fetchall()

def TotalInStore(sender,**kwargs):
....................
ItemsInOrder = """SELECT item_code_id as code,SUM(quantity) as total
FROM OrderDetail
GROUP BY item_code_id
ORDER BY item_code_id"""
SUMS = ExecuteQuery(ItemsInOrder)
if SUMS:
[Items.objects.filter(pk=t[0]).update(total_quantity_in_store=int(t[1])) for t in SUMS]
.............
return

To put it in a nutshell my Django 1.5.5 app 1):records the quantities of medical items given to patients of a medical center by means of an inline view that connects 'OrderDetail' to 'Order', 2): then input in the field total_quantity_in_store of the model 'Items' the sum of the field quantity ('OrderDetail') aggregated by item code via a post_save signal calling the TotalInStore function.
It works happily BUT .... unfortunately with the increasing numbers of record in 'OrderDetail' it is (and will be obviously) becoming slower and slower. This is due to the fact that the post_save signal - aggregating the quantities - by code is called for EACH OrderDetail record I have input in the inline view while it will be more logical to execute it ***after*** all records of the inline view have been saved.

Please help me modify my app so that the TotalInStore function is called only once after the inline view Order-OrderDetail has been saved.

Ciao
Vittorio

Vincenzo Prignano

unread,
Nov 8, 2013, 10:13:33 AM11/8/13
to django...@googlegroups.com
 I got that you are executing a raw sql query every time you insert a new OrderDetail record. But can I ask why are you doing this? 
I think you should really need to redesign your models..

Victor

unread,
Nov 9, 2013, 1:43:32 PM11/9/13
to django...@googlegroups.com
You're almost right. I want that - for each item_code - the sum aggregated by item_code of the items inserted into OrderDetail be automatically inserted into total_quantity_in_store by the same code in Items model.
Ciao
Vittorio
> --
> You received this message because you are subscribed to the Google Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/c1081e20-375a-4626-9b72-6582caad3a97%40googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.

Victor

unread,
Nov 9, 2013, 1:53:26 PM11/9/13
to django...@googlegroups.com
In my settings.py I have the following code:
.........
CACHES = {
'default': {
'BACKEND': 'johnny.backends.memcached.MemcachedCache',
# 'BACKEND': 'johnny.backends.memcached.CacheClass',
'LOCATION': ['127.0.0.1:11212'],
'JOHNNY_CACHE': True,
}
}

JOHNNY_MIDDLEWARE_KEY_PREFIX='vic_'

MIDDLEWARE_CLASSES = (
'johnny.middleware.LocalStoreClearMiddleware',
'johnny.middleware.QueryCacheMiddleware',
.........

Which worked like a charm till django 1.5.5.

Now, after installing the new django 1.6 when I launch 'python manage.py runserver' the following fatal error is signalled:


File "/Library/Python/2.7/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 6, in <module>
from django.contrib.staticfiles.handlers import StaticFilesHandler
File "/Library/Python/2.7/site-packages/django/contrib/staticfiles/handlers.py", line 8, in <module>
from django.contrib.staticfiles.views import serve
File "/Library/Python/2.7/site-packages/django/contrib/staticfiles/views.py", line 15, in <module>
from django.contrib.staticfiles import finders
File "/Library/Python/2.7/site-packages/django/contrib/staticfiles/finders.py", line 12, in <module>
from django.contrib.staticfiles.storage import AppStaticStorage
File "/Library/Python/2.7/site-packages/django/contrib/staticfiles/storage.py", line 8, in <module>
from django.core.cache import (get_cache, InvalidCacheBackendError,
File "/Library/Python/2.7/site-packages/django/core/cache/__init__.py", line 138, in <module>
cache = get_cache(DEFAULT_CACHE_ALIAS)
File "/Library/Python/2.7/site-packages/django/core/cache/__init__.py", line 130, in get_cache
"Could not find backend '%s': %s" % (backend, e))
django.core.cache.backends.base.InvalidCacheBackendError: Could not find backend 'johnny.backends.memcached.MemcachedCache': 'module' object has no attribute 'CacheClass'

Surfing the netI found a workaround for this error that applied to django 1.4 butturned out to be useless with 1.6.
Please help
Vittorio

Oak McIlwain

unread,
Jan 26, 2014, 7:51:57 PM1/26/14
to django...@googlegroups.com
Did you end up solving this issue?
Reply all
Reply to author
Forward
0 new messages