python - Django ImageField问题

标签 python django django-models

我有一个类似的模型

Class Student(models.Model):
"""A simple class which holds the basic info
of a student."""

name = models.CharField(max_length=50)
age = models.PositiveIntegerField()
photo = models.ImageField(upload_to='foobar', blank=True, null=True)

正如我们所见,照片字段是可选的。我想要所有将图像保存在大学数据库中的学生。为此我做了这个

>>> Student.objects.exclude(photo__name=None)

但是我收到了这个错误:

FieldError: Join on field 'photo' not permitted.

那么,我怎样才能提取所有拥有照片的学生?

如能提供任何有关此的帮助,我们将不胜感激。 提前致谢。

最佳答案

它不起作用,因为 field lookups仅适用于其他型号。此处,name 是您的 photo 字段返回值的一个属性。

试试这个:

Student.objects.exclude(photo__isnull=True)

最好使用 isnull 而不是将相等与 None 进行比较。

编辑:

Jeff Ober的建议:

Student.objects.exclude(photo='')

他说过滤是对存储在数据库中的实际值执行的。在文件字段的情况下,文件的路径。

关于python - Django ImageField问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/851830/

相关文章:

Python:打印用户输入的常见字母

Python 库 IP2location 回溯

django - 在 Django Rest 框架中发布请求处理

python - 无法在heroku中获取媒体文件

python - 如何从二进制文件中读取除最后 X 字节以外的所有字节?

python - Django休息框架: other URLs overwritten when including default router

python - RabbitMQ 或 Redis 使用 Django 2.0 扩展 Celery 队列

python - 从函数和前缀字符串在 Django 中创建默认 ID

python - Django 之外的 Django 模型

django - 跨应用程序使用 django 模型?