亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

詹戈:如何獲取外鍵ID?

詹戈:如何獲取外鍵ID?

弒天下 2022-09-27 09:40:38
我有2個模型如下class Product(models.Model):   product_name = models.CharField(max_length=100)   product_weight = models.CharField(max_length=30)class ProductImage(models.Model):   product = models.ForeignKey(Product, on_delete=models.DO_NOTHING)   image = models.ImageField(upload_to='/images/{product_id}/', blank=True)如何在產品圖像模型中提取product_id?提前致謝。
查看完整描述

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


查看完整回答
反對 回復 2022-09-27
?
qq_遁去的一_1

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()


查看完整回答
反對 回復 2022-09-27
?
慕蓋茨4494581

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)


查看完整回答
反對 回復 2022-09-27
  • 3 回答
  • 0 關注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號