python - 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()
解决方案
我已经在这里回答过这个问题,但是这就是你要找的
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)
信号可以提供帮助,但它们更难调试。
推荐阅读
- c# - C# MVC - 重新加载(获取)PartialView 在 href 上丢失完整的 URL 参数
- android - Android观察者模式和数据绑定,当布尔属性改变时启动活动
- java - 使改造省略未设置的查询参数
- java - Intellij idea libgdx java lambda 表达式在源代码中不受支持
- google-app-engine - 从提交到 GitHub 的更改触发新版本的 App Engine 应用程序
- scala - 无法使用 Scala 停止定义的递归函数
- eclipse - Oracle JDBC 异常,在 webapp 中,在 Tomcat 部署中:java.sql.DriverManager.getDriver 中没有合适的驱动程序
- javascript - React 反模式,定义一个组件里面定义另一个组件
- php - Laravel 5. String Var 子句不起作用的地方
- jsonpath - 如何为可能具有两种不同类型的元素指定替代 json 路径