我需要做一个计算项目价格而不将它们存储在数据库 django 中的函数

时间:2021-08-01 20:46:29

标签: python django

我需要做一个函数来计算商品的价格而不将它们存储在数据库中,因为商品的价格每天都在变化, 我已经划伤了当天的价格,我需要根据这个价格计算商品

models.py

class Product(models.Model):
    prdct_name = models.CharField(max_length=17, verbose_name=_("Article "))
    prdct_category = models.ForeignKey("Category", on_delete=models.CASCADE, blank=True, null=True)
    prdct_description = models.TextField(verbose_name=_("Description"))
    prdct_img = models.ImageField(upload_to='product/',verbose_name=_("Image"), blank=True, null=True)
    # prdct_img
    prdct_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name=_("Prix "))
    prdct_cost = models.DecimalField(max_digits=10, decimal_places=2, verbose_name=_("Prix promotionel "))
    prdct_weight = models.DecimalField(max_digits=10, decimal_places=2, verbose_name=_("Poid "))
    prdct_created = models.DateTimeField(auto_now=False, auto_now_add=False, verbose_name=_("Date Creation "))
    prdct_genre = models.CharField(max_length=50, verbose_name=_("Genre "))
    prdct_matiere = models.CharField(max_length=50, verbose_name=_("Matiere "))
    prdct_titrage = models.CharField(max_length=50, verbose_name=_("titrage "))
    prdct_in_stock = models.BooleanField(verbose_name=_("in_stock "))
    prdct_slug = models.SlugField(blank=True, null=True)

从网站上抓取价格的功能

def get_prixmatiere():
    # get price from cpor
    import requests
    from bs4 import BeautifulSoup
    response = requests.get("https://www.exampl.com")
    soup = BeautifulSoup(response.text , 'lxml')
    product_price = soup.find_all("td",{"class" : "price"})[0].text.replace('€', '').replace(' ', '')
    # calculate price
    prixdug = float(product_price) / 4 * 3 / 1000 * 210 - 500
    prixmatiere = float(product_price) / 4 * 3 / 1000 * 210
    return prixmatiere

我需要获取商品的价格

def calc_price_item(self):
    self.dailyprice = get_prixmatiere()
    item_price = self.prdct_price + self.dailyprice * self.prdct_weight
    return item_price

然后显示它

views.py

from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from .models import Product, ProductImage, Category
from django.core.paginator import Paginator




# function get all product
def product_list(request):
    product_list = Product.objects.all()[:5]        # get all product in variable le model doit etre importe depuis la class

    context = {
        'product_list' : product_list,       # contexte dictionaire variable qui contien les produit = product_list pour lutuliser dans les loupe dans le views
        
                }

    return render(request, 'Product/product_list.html', context)  # retourne la requete + le nom du dossier(dans le templates) + context



def product_detail(request, slug, id):
    product_detail = Product.objects.get(prdct_slug=slug)
    images = ProductImage.objects.filter(prdct_product_id=id)
    cat_parent = Category.objects.filter(level='0')


    context = {'product_detail' : product_detail,
                'images' : images,
                'cat_parent': cat_parent,
                }

    return render(request, 'Product/product_detail.html', context)



def category_product(request, id, slug):
    cat_slug = Category.objects.get(cat_slug=slug)
    category_product =  Category.objects.filter(parent_id=id)
    product = Product.objects.filter(prdct_category=id)

    paginator = Paginator(product, 20) # Show 20 contacts per page.

    page_number = request.GET.get('page')
    product = paginator.get_page(page_number)


    context = {

            'id' : id,
            'cat_slug' : cat_slug,
            'category_product': category_product,
            'product': product,

            }


    return render(request, 'Product/category_product.html', context)

1 个答案:

答案 0 :(得分:0)

我得到了我想要的东西

F() 表达式可用于在模型字段之间执行算术运算(+、-、* 等)

不要忘记导入模块 F

from django.db.models import F

views.py

prixmatiere = get_prixmatiere()
product_list = Product.objects.all()[:5].annotate(prixgram=F('prdct_price') + int(prixmatiere)).annotate(prixopiece=F('prixgram') * F('prdct_weight'))

现在 product_list 中的项目有一个名为 prixgram 的额外列,prixopiece 包含值