猿问

詹戈:如何获取外键ID?

我有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?


提前致谢。


弑天下
浏览 100回答 3
3回答

叮当猫咪

您可以通过在字段名称中添加“_id”来获取Django中任何外键的“原始”值obj = ProductImage.objects.get() obj.product_id  # Will return the id of the related product您也可以只关注关系,但如果尚未使用类似的东西缓存关系,这将执行另一个数据库查找select_relatedobj.product.id

qq_遁去的一_1

这是我到目前为止尝试并找到解决方案的方法。我发现实现的唯一选择是使用pre_save和post_save信号。以下是我如何实现解决方案。如果有人有不同的解决方案,请分享。谢谢。from django.db.models.signals import post_save, pre_savefrom 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()

慕盖茨4494581

只需在国外参考模型产品中添加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)
随时随地看视频慕课网APP

相关分类

Python
我要回答