根据类别django获取数据

时间:2019-09-04 10:51:13

标签: django python-3.x

我正在创建一个股票摄影门户,因此我在主页上列出了所有图像类别,当我单击任何类别时我想要的是它应根据类别获取数据 view.py:

def imageview(request):
    #cat_image = request.GET.get()
    allimage = image.objects.all()

    cat= category.objects.all()
    context = {'allimage': allimage, 'cat': cat}
    return render(request, 'image/search.html', context)

models.py:

class category(models.Model):
    name = models.CharField(max_length = 100)
    slug = models.SlugField()
    parent = models.ForeignKey('self',blank=True, null=True, 
             related_name='children', on_delete=models.CASCADE)

class Meta:
    unique_together = ('slug', 'parent') 
    verbose_name_plural = "categories"

def __str__(self):  
    full_path = [self.name]
    k = self.parent
    while k is not None:
        full_path.append(k.name)
        k = k.parent
    return ' -> '.join(full_path[::-1])

class image(models.Model):
    title = models.CharField(max_length = 100)
    image = models.ImageField(upload_to = 'home/tboss/Desktop/image') 
    default = 'home/tboss/Desktop/image/logo.png')
    category = models.ForeignKey('category', null=True, blank=True, 
               on_delete=models.CASCADE)
    description = models.TextField(max_length=1000)

def __str__(self):
    return self.title

urls.py:

urlpatterns = [
    path('', views.home, name = 'home'),
    path('search/', views.imageview, name= 'imageview')
]

我也试图包括基于类别的搜索。我不知道什么是最好的方法

1 个答案:

答案 0 :(得分:1)

为此,您需要先获取单个类别对象,然后才能获得该类别的所有图像,如下所示:

def category_images(request,pk):

    category = get_object_or_404(Category,pk=pk)
    images_in_that_category = category.image_set.all()
    return render(request,'template',{'images':images}

或者您可以像这样过滤:

    images_in_that_category = Image.objects.filter(category=category)