Django Class Based Views - 3

Model:

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=255)
    price = models.FloatField()
    stock = models.IntegerField()
    image_url = models.CharField(max_length=2083)
    discount_price = models.FloatField()
    description = models.CharField(max_length=255)

    def __str__(self):
        return self.name

 Urls:

from django.contrib import admin
from django.urls import path

from product.views import ProductDetailView

urlpatterns = [
    path('admin/', admin.site.urls),
    path("product/<int:id>/", ProductDetailView.as_view(), name="product-detail")
]

View:

from django.db.models import F
from django.shortcuts import render
from django.views.generic import DetailView

from product.models import Product


class ProductDetailView(DetailView):
    model = Product
    template_name = "product_detail.html"
    pk_url_kwarg = "id"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        return context
    
    def get_queryset(self):
        return super().get_queryset().annotate(
            total_price=F("price") - F("discount_price"),
        )
        

 

Html:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
price : {{ product.price }} <br>
discount price : {{ product.discount_price }} <br>
total price : {{ product.total_price }} <br>


</body>
</html>

Yorumlar

    Henüz Hiç Yorum Yapılmamış

Yorum Yap