Django:如何获取外键id?

2024-09-25 16:22:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个模型如下

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)

如何在ProductImage模型中提取产品标识

提前谢谢


Tags: name模型modelonmodelsproductdeletelength
2条回答

以下是我到目前为止所做的尝试,并找到了解决方案。我发现实现的唯一选择是使用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()

通过在字段名中添加“\u id”,可以获得Django中任何外键的“原始”值

obj = ProductImage.objects.get()
obj.product_id  # Will return the id of the related product

您也可以只跟踪关系,但是如果没有使用类似select_related的方法缓存关系,那么这将执行另一个数据库查找

obj.product.id

相关问题 更多 >