python - Django:如何获取外键ID?

标签 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)

如何在 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/

相关文章:

Linux 错误上的 Python 3.6 tkinter 窗口图标

python - numpy poly() 和 root() 不可逆吗?

具有 Django REST 框架的本地和 mod_wsgi 服务器之间的 Django JWT 身份验证行为不同

python - 使用 Apache/NginX 部署 Django Bad Request(400) 错误

django - nginx + uwsgi + django出现502错误

python - 基于约束的Dataframe列生成

python - 使用绝对值并除以决策变量的成本函数

ruby-on-rails - rails : Multiple "types" of one model through related models?

node.js - mongodb填充方法不起作用

ruby-on-rails - Rails - 放置非 Active Record 模型的位置(目录)