Show Last month progress of user on base of actions on website django

三世轮回 提交于 2019-12-11 05:22:03

问题


I have designed my database like this

user = models.ForeignKey(Profile, unique=True, on_delete=models.CASCADE)
signup = models.FloatField(default=10)
signup_from_user_link = models.FloatField(default=0)
post_review = models.FloatField(default=0)
total = models.FloatField(default=0)

I am calculating overall progress of user by adding all these values . But Now I have to make a change and I want to show progress of last month. Like in last month how much user added in every filed . What will be easiest way to get value of last month addition into these filed.

Any help would be highly appreciated. thanks


回答1:


You can create a model that stores the time of creation and a "value" for an event (like submitting a review), every time a user performs the action you create an instance of this model

class Action(models.Model):
    user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='actions')
    timestamp = models.DateTimeField(auto_now_add=True)
    value = models.FloatField()

You can then use aggregation to sum all the values for the event in the last month for a user with this query

total_for_last_month = user.actions.filter(
    timestamp__gt=datetime.datetime.now() - dateutil.relativedelta(months=1)
).aggregate(
    total=Sum('value')
)['total']

You would probably want to rename the model as "Review" or something and might want to add more fields

If you wish to calculate the total for a queryset of profiles then you can annotate each one

users = Profile.objects.filter(
    actions__timestamp__gt=datetime.datetime.now() - dateutil.relativedelta(months=1)
).annotate(
    total=Sum('actions__value')
)


来源:https://stackoverflow.com/questions/57648240/show-last-month-progress-of-user-on-base-of-actions-on-website-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!