Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于类别django获取数据_Django_Python 3.x - Fatal编程技术网

基于类别django获取数据

基于类别django获取数据,django,python-3.x,Django,Python 3.x,我正在创建一个股票摄影门户,所以我有一个主页,其中列出了所有的图像类别我想要什么,当我点击任何类别,然后它应该获取基于类别的数据 view.py: models.py: class category(models.Model): name = models.CharField(max_length = 100) slug = models.SlugField() parent = models.ForeignKey('self',blank=True, null=True

我正在创建一个股票摄影门户,所以我有一个主页,其中列出了所有的图像类别我想要什么,当我点击任何类别,然后它应该获取基于类别的数据 view.py:

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
URL.py:

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

此外,我还试图包括基于类别的搜索。我不知道做这件事的最佳方法是什么。为此,您需要先获得单个类别对象,然后才能获得该类别的所有图像,如下所示:

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)
或者,您可以这样进行筛选:

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)

如果您已经这样做了,您应该能够从给出的示例中找到解决方案。否则,您可能应该先学习教程;-)作为旁注:您可能还希望遵循约定并将类名大写。好的,每次我对类名或任何字段进行一些更改时,我都必须删除数据库中的所有表。有必要吗?或者有其他方法吗?Django有数据库迁移,您最好学会使用它们(说真的,这将为您节省大量时间和挫折)。但是仅仅更改模型名称的大小写不应该影响数据库模式,因为表名称(默认情况下)是从模型名称的小写版本构建的。最好在建立生产数据库之前尽快解决这些问题。。。