基于类别的列表在Django中查看

时间:2018-11-20 14:47:36

标签: python django

我有两个模型,第一个是类别,第二个是详细信息,我要查看一个可以单击一个类别的视图,该链接应该将我带到我单击的当前类别的列表。 我的模型给出了:

class FoodCategory(models.Model):
    categoryname = models.CharField(max_length=100)
    categorydetails = models.CharField(max_length=1000)
    categoryimage = models.ImageField(default='cat_def.jpg', 
    upload_to='catimg')

    class Meta:
        verbose_name = 'Food Category'

    def __str__(self):
        return self.categoryname


class FoodDetails(models.Model):
    fromcategory = models.ForeignKey(FoodCategory, 
    on_delete=models.CASCADE)
    foodname = models.CharField(max_length=100)
    fooddetails = models.CharField(max_length=1000)
    foodimage = models.ImageField(default='food_def.jpg', 
    upload_to='fodimg')
    armodel = models.CharField(default='andy.sfb', max_length=50)
    additiondate = models.DateTimeField(default=timezone.now)
    addedby = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta:
        verbose_name = 'Food Detail'

    def __str__(self):
        return self.fromcategory.categoryname + \
           ' - ' + self.foodname + \
           ' - ' + 'added by' + \
           ' - ' + self.addedby.username

    def get_absolute_url(self):
        return reverse('food-details', kwargs={'pk': self.pk})

views.py文件:

from django.shortcuts import render
from food.models import FoodCategory, FoodDetails
from django.views.generic import ListView, DetailView


class FoodCategoryView(ListView):
    model = FoodCategory
    template_name = 'food/food-category.html'
    context_object_name = 'food'


class FoodListView(ListView):
    model = FoodDetails
    template_name = 'food/food-list.html'
    context_object_name = 'food'

    ordering = ['-additiondate']


class FoodDetailsView(DetailView):
    model = FoodDetails
    template_name = 'food/FoodDetails_detail.html'

还有我的urls.py文件:

from django.urls import path, include
from . import views
from .views import FoodCategoryView, FoodListView, FoodDetailsView

# api url handler

urlpatterns = [
    path('category/', FoodCategoryView.as_view(), name='food- 
    category'),
    path('foodlist/', FoodListView.as_view(), name='food-list'),
    path('foodlist/<int:pk>/', FoodDetailsView.as_view(), 
    name='food-details')

]

这是我的所有文件,我只想知道一种获取当前基于类别的食物详细信息的特定方法。

1 个答案:

答案 0 :(得分:2)

您可以通过在列表视图上定义get_queryset来实现。

class FoodDetailsByCategory(ListView):
    def get_queryset(self):
        return FoodDetails.objects.filter(fromcategory_id=self.kwargs['category_id'])

具有简单的网址:

path('category/<int:category_id>', FoodDetailsByCategory.as_view(), name='food_details_by_category')