首页 > 解决方案 > Django - 创建新对象时更新 ForeignKey

问题描述

当图像添加到数据库时,我正在尝试更新我的外键,如果高度大于宽度,则只是简单地标记图像,反之亦然。为此,我试图覆盖 save 方法,但我不知道该怎么做。

楷模:

from PIL import Image

class PhotoDimensionsCategory(models.Model):
     photo_dim_category = models.CharField(max_length=250)

class ImageInGallery(models.Model):
     image = models.ImageField(upload_to='photos/')
     gallery_dim = models.ForeignKey(PhotoDimensionsCategory, on_delete=models.CASCADE)

     def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

        img = Image.open(self.image.path)
        on_height = PhotoDimensionsCategory.objects.get(photo_dim_category='on_height')
        on_width = PhotoDimensionsCategory.objects.get(photo_dim_category='on_width')
        is_new = not self.pk

        if img.height > img.width and is_new:
               # set the gallery_dim to on_height
        else
               # set the gallery_dim to on_width

我尝试了几件事,但以错误告终。有任何想法吗。谢谢。

编辑:

如果我尝试使用信号,它不会做任何事情:

@receiver(post_save, sender=ImageInGallery)
def set_dim(sender, instance, created, **kwardgs):
if created:
    instance.gallery_dim.photo_dim_category = 'on_height'
    instance.save()

标签: pythondjango

解决方案


我已经在这里回答过这个问题,但是这就是你要找的

   def save(self, *args, **kwargs):
        old_pk = self.pk # pk is created on saving, We didn't call super().save() yet!
        # so the pk should be None if this is the creation phase.

        if old_pk is None:
            # do something, Only at the first save 
        super().save(*args, **kwargs)

信号可以提供帮助,但它们更难调试。


推荐阅读