2017-05-15 107 views
0

我想從每個用戶的字段中獲取數據(amount_spent),並將這些數字向上添加並從另一個模型(RevenueInfo)的另一個字段(total_revenue)中顯示它們。從另一個模型的數據計算Django模型中的數字

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_spenttotal_revenue,但我覺得我需要一個ForeignKey

回答

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')} 
+0

對不起,遲到的答覆,謝謝你的作品。但是,將是最好的方式顯示在管理頁面/在實際領域?基本上我需要像'models.DecimalField('amount_spent')之類的東西。顯然這不起作用,但你知道我的意思 – Amon

+0

我在想我可以從返回的字典中檢索整型,並將其中一個字段的默認值設置爲? – Amon

+1

需要澄清才能完全遵循你的要求。如果這是用於參考和比較各個用戶字段,那麼您可以通過在django admin https://docs.djangoproject.com/en/1.11/ref中添加使用「fieldsets」的描述來顯示ExtendedProfile表單上的總支出/了contrib /管理/,例如: – birophilo

1

是的,你可以在你的模型中編寫一個方法。有2種方式。 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) 

而對於使用意見認爲值,但reme​​ber這將是一個整數默認

#views.py 
value = RevenueInfo.total_amount_spent() 
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 
相關問題