use*_*041 3 python django model foreign-keys
我有 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)
Run Code Online (Sandbox Code Playgroud)
如何在 ProductImage 模型中提取 product_id?
提前致谢。
您可以通过在字段名称中添加“_id”来获取 Django 中任何外键的“原始”值
obj = ProductImage.objects.get()
obj.product_id # Will return the id of the related product
Run Code Online (Sandbox Code Playgroud)
您也可以只关注关系,但如果尚未使用类似的方法缓存关系,这将执行另一个数据库查找 select_related
obj.product.id
Run Code Online (Sandbox Code Playgroud)