Add all values ​​to queryset in Django

I am writing a django application that has two classes, an overview and an answer to the mentioned overview. The answer is stored in a ManyToMany field in the overview.

This is my class for review:

class Review(models.Model):
    title = models.CharField(max_length = 30)
    replies = models.ManyToManyField(Reply)

    def __str__(self):
        return self.title

      

And here is my response class:

class Reply(models.Model):
    rating = models.DecimalField(decimal_places=1, 
                                 max_digits = 2,
                                 validators = [MaxValueValidator(5), MinValueValidator(0)],
                                 default = 0
                                )
    text_reply = models.TextField(max_length = 200)

      

One of the things I want to do is take all the ratings for a particular review and calculate the average of those numbers. I tried to do this by doing the following:

def calculate_average():
    objects = Review.objects.all()
    average = 0
    length = 0
    for reply in objects:
        average += reply.replies.rating
        length += 1
    return average/length

      

Traceback

C:\Users\Will Treston\gd\LesRev\lesssonreview>python manage.py runserver
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03363540>
Traceback (most recent call last):
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run
    autoreload.raise_last_exception()
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception
    six.reraise(*_exception)
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 115, in populate
    app_config.ready()
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\apps.py", line 23, in ready
    self.module.autodiscover()
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover
    autodiscover_modules('admin', register_to=site)
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\module_loading.py", line 50, in autodiscover_modules
    import_module('%s.%s' % (app_config.name, module_to_search))
  File "C:\Users\Will Treston\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "C:\Users\Will Treston\gd\LesRev\lesssonreview\review\admin.py", line 5, in <module>
    class ReviewAdmin(admin.ModelAdmin):
  File "C:\Users\Will Treston\gd\LesRev\lesssonreview\review\admin.py", line 8, in ReviewAdmin
    list_display = ["title", Review.calculate_average()]
  File "C:\Users\Will Treston\gd\LesRev\lesssonreview\review\models.py", line 46, in calculate_average
    average += reply.replies.rating
AttributeError: 'ManyRelatedManager' object has no attribute 'rating'

      

+3


source to share


1 answer


To calculate the rating for a specific review

result = {}
objects = Review.objects.all()
for review in objects:
    average = 0
    length = 0
    for reply in review​.replies.all():
        average += reply.rating
        length += 1
    average /= length
    result.update({review.title, average})

      



If you are looking for a model attribute to compute the same model then

class Review(models.Model):

    def calculate_rating(self):
        average = 0
        length = 0
        for reply in self​.replies.all():
            average += reply.rating
            length += 1
        if average:
            average /= length
        return average

      

+1


source







All Articles