3 回答
TA贡献1776条经验 获得超12个赞
您可以通过在字段名称中添加“_id”来获取Django中任何外键的“原始”值
obj = ProductImage.objects.get() obj.product_id # Will return the id of the related product
您也可以只关注关系,但如果尚未使用类似的东西缓存关系,这将执行另一个数据库查找select_related
obj.product.id
TA贡献1725条经验 获得超7个赞
这是我到目前为止尝试并找到解决方案的方法。我发现实现的唯一选择是使用pre_save和post_save信号。以下是我如何实现解决方案。如果有人有不同的解决方案,请分享。谢谢。
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
_UNSAVED_IMAGEFIELD = 'unsaved_imagefield'
def upload_path_handler(instance, filename):
import os.path
fn, ext = os.path.splitext(filename)
return "images/{id}/{fname}".format(id=instance.product_id,
fname=filename)
class ProductImage(models.Model):
product = models.ForeignKey(Product, on_delete=models.DO_NOTHING)
image = models.ImageField(upload_to=upload_path_handler, blank=True)
@receiver(pre_save, sender=ProductImage)
def skip_saving_file(sender, instance, **kwargs):
if not instance.pk and not hasattr(instance, _UNSAVED_IMAGEFIELD):
setattr(instance, _UNSAVED_IMAGEFIELD, instance.image)
instance.image = None
@receiver(post_save, sender=ProductImage)
def update_file_url(sender, instance, created, **kwargs):
if created and hasattr(instance, _UNSAVED_IMAGEFIELD):
instance.image = getattr(instance, _UNSAVED_IMAGEFIELD)
instance.save()
TA贡献1850条经验 获得超11个赞
只需在国外参考模型产品中添加str函数即可。
class Product(models.Model):
product_name = models.CharField(max_length=100)
product_weight = models.CharField(max_length=30)
def __str__(self):
return str(self.id)
添加回答
举报