我有两种模式:
class A(models.Model):
title = models.CharField(max_length=100)
a_bg_img = models.ImageField(upload_to='./bg/')
class A_B(models.Model):
title = models.CharField(max_length=100)
b_bg_img = # this should just refer to A's a_bg_img field
b_bg_img
应该只引用a_bg_img
字段,这样我就不会保存一张图片两次。我可以这样说:
b_bg_img = models.TextField()
然后只保存a_bg_img
中图片的链接?
答案 0 :(得分:0)
如果您有与A类对象关联的图像,则可以使用.path
(或get_path()
)或.url
轻松检索该图像的路径或该图像的网址
例如:
a = A.objects.get(id=1)
print(a.a_bg_img.path)
'/path/to/image/in/your/local/drive/image.jpg'
print(a.a_bg_img.get_path())
'/path/to/image/in/your/local/drive/image.jpg'
print(a.a_bg_img.url)
'/url/to/your/image'
答案 1 :(得分:-1)
您可以使用django信号post_save在模型保存()后执行操作
怎么样?
__init__.py
from django.dispatch import receiver
from django.db.models.signals import post_save
@receiver(post_save, sender=A)
def my_action(sender, instance, **kwargs):
# Your function magic