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條經驗 獲得超8個贊
這是我到目前為止嘗試并找到解決方案的方法。我發現實現的唯一選擇是使用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)
添加回答
舉報