Created
February 11, 2013 17:32
-
-
Save saippuakauppias/4755991 to your computer and use it in GitHub Desktop.
Django: denormalization in models vs. raw sql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
from django.db.models import signals | |
from django.utils.translation import ugettext_lazy as _ | |
from .signals import update_thumbnail_image | |
class Gallery(models.Model): | |
title = models.CharField(_('title'), max_length=50) | |
thumbnail = models.ImageField(_('thumbnail'), | |
upload_to='galleries/gallery', | |
editable=False) | |
images_count = models.PositiveIntegerField(_('images count'), | |
editable=False, | |
default=0) | |
class Meta: | |
ordering = ('-images_count',) | |
verbose_name = _('gallery') | |
verbose_name_plural = _('galleries') | |
def __unicode__(self): | |
return self.title | |
def update_images_count(self): | |
self.images_count = self.images.count() | |
self.save() | |
update_images_count.alters_data = True | |
class Image(models.Model): | |
gallery = models.ForeignKey('galleries.Gallery', related_name='images') | |
title = models.CharField(_('title'), max_length=50) | |
image = models.ImageField(_('image'), upload_to='galleries/image') | |
class Meta: | |
verbose_name = _('image') | |
verbose_name_plural = _('images') | |
def __unicode__(self): | |
return self.title | |
def save(self, *args, **kwargs): | |
super(Image, self).save(*args, **kwargs) | |
self.gallery.update_images_count() | |
signals.post_save.connect(update_thumbnail_image, sender=Image) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db.models import ImageField | |
def update_thumbnail_image(instance, **kwargs): | |
if kwargs.get('raw', False): | |
return | |
# могу ошибаться в строчке ниже, вроде обязательно надо save=False | |
instance.gallery.thumbnail = ImageField(instance.image, save=False) | |
instance.gallery.save() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment