这是我的模型(简化):
class Book(models.Model):
title = models.CharField(max_length=200)
...
img_1 = models.ImageField(null=True)
img_2 = models.ImageField(null=True)
img_3 = models.ImageField(null=True)
我有一个post_save信号:
@receiver(post_save, sender=Book)
def meli_publicar_signal(sender, instance, **kwargs):
if kwargs.get('created', True):
# get images
我想要的是获取所有图像字段(img_1,img_2等)并检查它们是否为空。
答案 0 :(得分:1)
我建议您使用Many-to-one relationships将图片链接到Book
个对象。它会比实际更有活力。
这是一个例子:
class Book(models.Model):
title = models.CharField(max_length=200)
# other fields
def __str__(self):
return self.title
class BookImage(models.Model):
image = models.ImageField(upload_to="images/")
book = models.ForeignKey(Book, related_name="images")
def __str__(self):
return self.image.url
现在,您不必在保存之前检查图片是否为空,因为您无法将BookImage
添加到Book
,因为image
和book
属性没有将null
参数设置为True
。
然后,获取Book
对象的URL:
@receiver(post_save, sender=Book)
def meli_publicar_signal(sender, instance, **kwargs):
for image in instance.images.all():
print(image.image.url)
# output : /media/images/filename.png
**注意:如果您更新字段,created
设置为False
,则它不会处理if kwargs.get('created', True):
下的代码。
如果您想保留没有BookImage
对象的基础模型,那么您可以这样做:
@receiver(post_save, sender=Tel)
def meli_publicar_signal(sender, instance, **kwargs):
for attr, value in instance.__dict__.items():
if isinstance(value, ImageFieldFile) and value:
print(value.url)
# output : /media/images/filename.png
阅读ImageField文档以获取更多信息
答案 1 :(得分:0)
要获取所有为图像的字段并检查它们是否为空创建方法:
from django.db import models
def get_image_fields_values(obj):
try:
image_fields = [getattr(obj, f.name, None)
for f in obj._meta.get_fields()
if isinstance(f, models.ImageField)]
# => [<ImageFieldFile: None>, <ImageFieldFile: movie/g-men.jpg>]
image_values = [image.name for image in image_fields if image.name]
# => ['movie/g-men.jpg']
except AttributeError:
return []
return image_values
然后在post_save信号中调用该方法,如:
@receiver(post_save, sender=Book)
def meli_publicar_signal(sender, instance, **kwargs):
if kwargs.get('created', True):
images = get_image_fields_values(obj=instance)