Django average scores with through -



Django average scores with through -

maybe newbie question, stuck in point. not know if problem model or not understand aggregations , annotations.

i have model this:

class user(models.model): collection = models.manytomanyfield(book, through='bookcollection') class book(models.model): name = models.charfield(max_length=200) class bookcollection(models.model): user = models.foreignkey(user) book = models.foreignkey(book) score = models.integerfield(default=0)

i want score average books , users, excluding ones has default score equals 0 (this value represents user has book in collection, has not been rated). trying utilize annotation this:

book.objects.exclude(collection__score=0).annotate(avg=avg('collection__score'))

but if there book rated 0 , 3, example, both entries excluded.

is there way tell avg() should take business relationship values greater 0?

thanks in advance.

there no way in django orm without raw sql.

a improve model allow null values in score field. null values ignored in avg():

class bookcollection(models.model): ... score = models.integerfield(null=true, blank=true, default=none)

none best way describe lack of entry in field. avoids confusion, e.g. in calculations such calculating average.

django

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -