Monday, June 30, 2014

How to simplify this code - newbie question

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 :)

--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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/007ec8b7-4ab9-460e-bf3e-06c14f91b5db%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment