我想从每个用户的字段中获取数据(amount_spent
)并添加这些数字并将其显示在来自其他模型(total_revenue
)的其他字段(RevenueInfo
)中。
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
from django import forms, views
# Create your models here.
#LoginInfo is being used, LoginForms in forms.py is
class LoginInfo(models.Model):
username = models.CharField('', max_length=10)
password = models.CharField('', max_length=15)
class ExtendedProfile(models.Model):
user = models.OneToOneField(User)
amount_spent = models.DecimalField(max_digits=6, decimal_places=2)
class RevenueInfo(models.Model):
total_amount_spent = models.DecimalField(max_digits=6, decimal_places=2, default=0)
total_revenue = models.ForeignKey(ExtendedProfile, null=True)
class Product(models.Model):
category = models.CharField(max_length=100)
name = models.CharField(max_length=100)
description = models.TextField()
#photo = models.ImageField()
price_CAD = models.DecimalField(max_digits=6, decimal_places=2)
quantity = models.DecimalField(max_digits=2, decimal_places=0, null=True)
我怎么能这样做?我会迭代每个User
模型并找到User.amount_spent
然后将其添加到RevenueInfo.total_revenue
吗?我不知道如何将其放入代码中。此外,我非常确定我不需要total_amount_spent
和total_revenue
,但我觉得我需要ForeignKey
答案 0 :(得分:1)
是的,您可以在模型中为其编写方法。它有两种方式。 1)编写一个计算值并将其设置为实例值的方法。 2)编写一个计算值并直接返回它的方法。
例如,这是第二种类型的代码。
# models.py
def total_amount_spent(self):
temp_values = [int(user.amount_spent) for user in ExtendedProfile.objects.all()]
return sum(temp_values)
并且在视图中使用该值,但记住它默认为整数
#views.py
value = RevenueInfo.total_amount_spent()
答案 1 :(得分:1)
避免在python中迭代数据库实体(它可能变得非常慢)。查看aggregation,它可以让您有效地获取数据库中值的总和(平均值,最大值,最小值等):
>>> from django.db.models import Sum
>>> ExtendedProfile.objects.all().aggregate(Sum('amount_spent'))
{'amount_spent__sum': Decimal('1234.56')}
>>> # ... do whatever you want with the return value
答案 2 :(得分:1)
您可以向classmethod
模型添加ExtendedProfile
,以便为每个用户聚合amount_spent
值(这会绕过对单独的RevenueInfo
模型的需求):
from django.db.models import Sum
class ExtendedProfile(models.Model):
....
@classmethod
def total_user_spend(cls):
return cls.objects.aggregate(total=Sum('amount_spent'))
然后,您可以使用ExtendedProfile.total_user_spend()
获得总支出:
>>> ExtendedProfile.total_user_spend()
{'total': Decimal('1234.00')}