These are chat archives for django/django

27th
Feb 2016
Yanik Koval
@yanikkoval
Feb 27 2016 11:15
@megapctr , res['Body'] is not iterable. Its botocore StreamingBody
Arcady Usov
@itcrab
Feb 27 2016 15:50
@megapctr i need hide any categories with products (show only categories with 0 products) in TreeForeignKey-field in Django admin - first idea store count in all categories and for field get categories with count = 0
@i2xS thank's i will see this
Arcady Usov
@itcrab
Feb 27 2016 18:21
@megapctr i do all in your answer way:
class Category(MPTTModel):
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
    count_products = models.IntegerField('Count of products', default=0)
    ...

class Product(models.Model):
    # When changing Category in Product save last value for recalc counts
    category_old_id = 0

    category = TreeForeignKey(Category, related_name='category', db_index=True)
    ...


def recalc_count_products(category_id):
    count_products = Product.objects.filter(category__id=category_id).count()
    Category.objects.filter(id=category_id).update(count_products=count_products)



@receiver(pre_save, sender=Product)
def get_old_category_id(sender, instance, **kwargs):
    """
    Getting old category id
    """
    if instance.pk is not None:
        try:
            product_in_db = Product.objects.get(id=instance.id)
        except Product.DoesNotExist:
            pass

        if product_in_db:
            if instance.category.id != product_in_db.category.id:
                instance.category_old_id = product_in_db.category.id


@receiver(post_delete, sender=Product)
@receiver(post_save, sender=Product)
def counts_update_posts(sender, instance, **kwargs):
    """
    Updating counts of Products in Category
    """
    if instance.category_old_id > 0:
        recalc_count_products(instance.category_old_id)

    recalc_count_products(instance.category.id)
@megapctr your way for me sounds very good and give all needed features
@megapctr thank's!
Filip Figiel
@megapctr
Feb 27 2016 18:48
Always happy to help :)
Arcady Usov
@itcrab
Feb 27 2016 18:52
@megapctr in start i want find any done application for this task but then i want do this myself (i have time on this task) - everything worked out :smile:
Arcady Usov
@itcrab
Feb 27 2016 19:46
@i2xS https://github.com/django-denorm/django-denorm from pip install don't work in Python 3.5.x (develop branch works but I needed only stable versions)