Django - Add field to queryset to store computation results

后端 未结 2 1922
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 12:39

I\'m pretty new to Django and come from the PHP world. I\'m trying to \'add\' a field to a queryset after computing things, and don\'t know how to do it. In PHP I would just add

相关标签:
2条回答
  • 2021-02-04 13:11

    You can set anything on a python object:

    for obj in self.model.objects.all() :
        obj.score = total_score / total_posts
    

    This will work even if obj does not have a score attribute. In the template request it like so:

    {{ obj.score }}
    

    Yes, it's that simple. However, if the calculations you're doing can be done in the database, you should look into annotate.

    0 讨论(0)
  • 2021-02-04 13:22

    Why not use a dictionary?

    newthing = {}
    newthing['your_key'] = to_add
    

    In the template, you can access dictionary values with:

    {{newthing.your_key}}
    

    Or use the for loop if you have a dictionary of dictionaries

    0 讨论(0)
提交回复
热议问题