我有 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)
如何在 ProductImage 模型中提取 product_id?
提前致谢。
最佳答案
您可以通过在字段名称中添加“_id”来获取 Django 中任何外键的“原始”值
obj = ProductImage.objects.get()
obj.product_id # Will return the id of the related product
您也可以只关注关系,但如果尚未使用
select_related
之类的东西缓存关系,这将执行另一个数据库查找obj.product.id
关于python - Django:如何获取外键ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61018027/