How to simplify this code - newbie question

49 views
Skip to first unread message

Michael Lind Hjulskov

unread,
Jun 30, 2014, 5:57:12 AM6/30/14
to django...@googlegroups.com
Hi :o)

I would like to simplify get_rating to fewer lines of code:

class Product(AbstractProduct):

    ... just a little info about the model fields ...
    title = charfield
    parent = foreignkey(Product, related_name='variants')
    rating = a float
    def is_group - return True if it is a parent product and have variants 
    ...

    @property
    def get_rating(self):
        u"""Return a product's rating - group product's ratings is gathered and presented as one"""
        if self.is_group:
            ratings_count = 0
            if self.rating:
                ratings_sum = self.rating
                ratings_count+=1
            for variant in self.variants.all():
                if variant.rating:
                    ratings_sum += variant.rating
                    ratings_count+=1

            if ratings_count > 0:
                rating = float(ratings_sum) / ratings_count
                return rating
        return self.rating


My best guess is below, but it isnt working.
Will somebody please teach me what I should do and maybe explain to me why it isnt working.
I really want to learn this :o)

class Product(AbstractProduct):

    @property
    def get_rating(self):
        u"""Return a product's rating - group product's ratings is gathered and presented as one"""
        if self.is_group:
            return float(Product.objects.filter(Q(parent__in=self) | Q(pk=self.pk)).aggregate(Avg('rating')))
        return self.rating


Thanks alot :)
Reply all
Reply to author
Forward
0 new messages