Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.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
Python 按高度/方向对图像进行排序_Python_Django_Django Views - Fatal编程技术网

Python 按高度/方向对图像进行排序

Python 按高度/方向对图像进行排序,python,django,django-views,Python,Django,Django Views,我用网格视图创建了图像库,但我不喜欢行的样子——垂直照片会破坏一切。由于我不想手动更改图像顺序,所以我正在寻找一种方法,通过图像高度或图像方向自动对它们进行排序,使垂直照片在一行中位于底部 这就是我在Django的模型的样子: class Photo(models.Model): title = models.CharField(max_length=150) image = models.ImageField() description = models.TextFie

我用网格视图创建了图像库,但我不喜欢行的样子——垂直照片会破坏一切。由于我不想手动更改图像顺序,所以我正在寻找一种方法,通过图像高度或图像方向自动对它们进行排序,使垂直照片在一行中位于底部

这就是我在Django的模型的样子:

class Photo(models.Model):
    title = models.CharField(max_length=150)
    image = models.ImageField()
    description = models.TextField(blank=True)
    category = models.IntegerField(choices=CATEGORIES)
    published = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.title
这是我的网格视图:

def photos_grid(request):
    global cat_list
    photos = Photo.objects.order_by('published')
    output = {'photos': photos, 'categories': cat_list,}
    return render(request, 'photos/photos_grid.html', output)
我尝试了那种()获取图像尺寸的方法,但是我得到了

ValueError: invalid literal for int() with base 10: 'height'

我试着把它放到我的代码里。其他想法(通过在
视图.py中手动获取尺寸)也行得通,但我无法将其与列表中的照片放在一起,以便对其进行排序。

您必须在模型中包含高度和宽度字段,例如:

class Photo(models.Model):
    image = models.ImageField(height_field='image_height', width_field='image_width')
    image_height = models.IntegerField()
    image_width = models.IntegerField()
    ...
迁移数据库后,可以编写以下内容:

Photo.objects.all().order_by('image_height')
编辑:如果需要访问方向,请添加另一个字段,例如:

class Photo(models.Model):
    ...
    aspect_ratio = models.FloatField(blank=True, null=True)
Photo.objects.all().order_by('aspect_ratio')
然后,重写保存方法,使用高度和宽度填充此字段,即:

class Photo(models.Model):
    ...
    def save(self, **kwargs):
        self.aspect_ratio = float(self.image_height) / float(self.image_width)
        super(Photo, self).save(kwargs)
然后,您可以按新字段排序,例如:

class Photo(models.Model):
    ...
    aspect_ratio = models.FloatField(blank=True, null=True)
Photo.objects.all().order_by('aspect_ratio')

你有没有想过使用Sorl先裁剪所有照片,然后去掉无用的查询?是的,但是有些照片裁剪时看起来不太好-我不久前在Facebook上遇到过这个问题,我讨厌照片的重要部分在缩略图上看不到。然后将几何体添加到模型中,即偏移x和偏移y。和作物分别。像这样: