2016-05-19 34 views
0

爲了說明這個問題,我建議考慮一下我的應用程序的簡化版本。如何組織項目以獲取特定用戶類型的產品價格?

假設有一個產品型號:

# products/models.py 
from django.db import models 

class Product(models.Model): 
    name = models.CharField(max_length=128) 
    retail_price = models.DecimalField(max_digits=8, decimal_places=2) 

和自定義用戶模型:

# authentication/models.py 
from django.db import models 
from django.contrib.auth.models import AbstractUser 

class ClientType(models.Model): 
    name = models.CharField(max_length=128) 
    part_of_retail_price = models.DecimalField(max_digits=4, decimal_places=3) 


class Client(AbstractUser): # custom user model 
    client_type = models.ForeignKey(ClientType) 

我希望能夠得到一個特殊的價格爲特定類型的用戶模板:

{% for product in products %} 
    {{ product.user_price }} 
{% endfor %} 

授權用戶價格等於product.retail_price和request.user.client的乘積_type.part_of_retail_price,僅針對未授權的product.retail_price。

實施它的最佳方法是什麼?我會很感激任何提示和幫助。

+0

一種方法是編寫乘以正確的因子值自定義過濾器。然後,您可以在模板中使用它,例如'{{product.user_price | user_price}}' – Selcuk

回答

0

如果您只需要一次顯示一個或幾個Client實例的值,最簡單的方法是使用模板過濾器,如@Selcuk的評論建議的{{ product.user_price|user_price }}

如果您需要QuerySet中的值來處理(排序等),請使用管理器以及annotate()ExpressionWrapper()

class ProductManager(models.Manager): 

    def for_user(self, user): 
     # Calculate the price here 
     user_price = user.user.client_type.part_of_retail_price 

     return self.annotate(user_price=ExpressionWrapper(
      Value(user_price), output_field=FloatField())) 

class Product(models.Model): 
    # ... 

    objects = ProductManager() 

然後,當您在您的視圖加載產品查詢集,添加當前用戶

products = Product.objects.all().for_user(request.user) 

user_price添加到常規查詢集,並根據需要,你可以在你的模板中使用它。

{% for product in products %} 
    {{ product.user_price }} 
{% endfor %} 
相關問題