首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带参数、非干的Django自定义模型方法

带参数、非干的Django自定义模型方法
EN

Stack Overflow用户
提问于 2020-05-11 07:25:40
回答 1查看 43关注 0票数 0

经过大量的研究和麻烦,我想出了一种非干性的解决方案,希望有人能把它弄干。

所有我试图得到的是一个计算价格,它接受一个参数,并相应地显示在模板中。我在model vehiclecategory上有一个函数get_price,它接受来自前端表单的参数持续时间。

MODELS.PY

代码语言:javascript
复制
class VehicleCategory(models.Model):

    CATEGORY_CHOICES=(
        ('E-Cycle', 'E-Cycle'),
        ('E-Scooter', 'E-Scooter')
    )
    
    main_category = models.CharField(max_length=15, choices= CATEGORY_CHOICES)
    title = models.CharField(unique=True, max_length=200)
    image = models.ImageField(
        null=True,
        blank=True,
        width_field="width_field",
        height_field= "height_field",
        default= 'e-bike.png',
        upload_to='category')
    width_field = models.IntegerField(default=250)
    height_field = models.IntegerField(default=250) 
    slug =models.SlugField(max_length=200, db_index=True, unique=True)

    
    def __str__(self):
        return self.title
   
    #GET PRICE
    def get_price(self, duration):
        for item in VehiclePrice.objects.all():
            if item.vehicle_category.title == self.title and (duration >= item.slab.start and duration <= item.slab.end):
                return item.total_price
        
    class Meta():   
        verbose_name = "Vehicle Category"
        verbose_name_plural = "Vehicle Categories"


class PriceSlab(models.Model):

    start = models.IntegerField()
    end = models.IntegerField()
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '%s - %s ' % (self.start, self.end)



class VehiclePrice(CustomerStatus):

    help_text= "Ensure no more than 2 digits after decimal"
    vehicle_category = models.ForeignKey(VehicleCategory, on_delete= models.SET_NULL, null=True,         related_name='vehicle_category_price')
    slab = models.ForeignKey(PriceSlab, on_delete=models.CASCADE)
    net_price = models.DecimalField(help_text= help_text, max_digits=5, decimal_places=2)
    tax_percent = models.DecimalField(help_text=help_text, max_digits=4, decimal_places=2,   default=18.00)
    discount_percent = models.DecimalField(help_text=help_text,max_digits=4, decimal_places=2, default=0, blank=True)
    
    
    @property
    def total_tax(self):    
        tax = (self.net_price * self.tax_percent)/100
        return tax

    @property
    def get_price(self):
        total = self.net_price  + self.total_tax
        return total 

    @property
    def total_discount(self):
        discount = (self.get_price * self.discount_percent)/100
        return discount

    @property
    def total_price(self):
        total = self.get_price - self.total_discount
        
        return round(total)

    class Meta():
        unique_together=('customer_status','vehicle_category' ,'slab')

    def __str__(self):
        return '%s - %s - %s' % (self.customer_status, self.vehicle_category, self.slab)

VIEWS.PY

代码语言:javascript
复制
class HomeView(ListView):

    template_name = 'app/home.html'

    def get(self, request): 
        

        if request.method == "GET":
            start_date =  request.GET.get('start_date')
            end_date =  request.GET.get('end_date')

            if start_date and end_date:
                start_date = datetime.strptime(start_date, "%d/%m/%Y").date()
                end_date = datetime.strptime(end_date, "%d/%m/%Y").date()

                duration = (end_date - start_date).days +1
                print(duration)
                
                vehiclecategory= VehicleCategory.objects.all()
                

                context = {
                    'price1': VehicleCategory.objects.get(main_category= 'E-Cycle',    title="Sporty").get_price(duration),
                    'price2': VehicleCategory.objects.get(main_category= 'E-Cycle', title="Step-Through").get_price(duration),
                    'price3': VehicleCategory.objects.get(main_category= 'E-Cycle', title="Fatbike").get_price(duration),
                    'price4': VehicleCategory.objects.get(main_category= 'E-Scooter', title="Scooter").get_price(duration),
                   
                    'vehiclecategory1': vehiclecategory.filter(main_category= 'E-Cycle', title="Sporty"),
                    'vehiclecategory1': vehiclecategory.filter(main_category= 'E-Cycle', title="Step-Through"),
                    'vehiclecategory1': vehiclecategory.filter(main_category= 'E-Cycle', title="Fatbike"),
                    'vehiclecategory2': vehiclecategory.filter(main_category= 'E-Scooter', title="Scooter"),
                   
                    'form':CartQuantityForm(),
                    'dateform': DateForm(),
                }
            else:
                context={'dateform': DateForm(),}

        

            return render(request, self.template_name, context )

在用户输入日期范围后,车辆就会显示出来,但是当你走到购物车并返回相同的页面时,页面会刷新为一个新页面。如何保持日期范围值不变,并呈现与用户第一次搜索车辆相同的页面,以便他可以添加或修改所选车辆?

EN

回答 1

Stack Overflow用户

发布于 2020-05-11 08:34:09

您可以将开始日期和结束日期放入您的URL中。

您可以创建两个urls记录,发送相同的视图:

代码语言:javascript
复制
   path(r'/prices/', HomeView.as_view())
   path(r'/prices/(?P<start>\d{4}-\d{2}-\d{2})_(?P<end>\d{4}-\d{2}-\d{2})', HomeView.as_view())

然后,您需要对您的观点做一些更改:

代码语言:javascript
复制
class HomeView(ListView):

    template_name = 'app/home.html'

    def get(self, request, **kwargs):
        start = kwargs.get('start')
        end = kwargs.get('end')

        if start is None or end is None:
            # Ask for dates & Redirect to its new url with dates.

        else:
            # Check the dates, convert them to date object & do the rest. 

也许不是最好的解决方案,但我想到的第一件事就是这个。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61724347

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档