【问题标题】:Get the id of a model object which is FK of another model object django获取模型对象的 id,它是另一个模型对象 django 的 FK
【发布时间】:2020-10-31 03:04:48
【问题描述】:

我有一个名为 WarehouseProduct 的模型,它有一个字段 warehouse_id,它是 Warehouse 模型的 FK,我需要获取该warehouse_id,以便它返回该 FK Warehouse 的 id。我尝试使用:

def __int__(self):
    return self.id

返回 WareHouse 对象 (6),另一种方式:

def __str__(self):
    return str(self.id)

返回 id,但类型是 Warehouse,所以我无法将其转换为 int 以供进一步使用。

【问题讨论】:

  • warehouse_id.id 当仓库的主键是默认值或类似整数的字段时,总是返回一个int。

标签: django python-class


【解决方案1】:

可以通过views中的values()和first()函数获取ant id

WarehouseProduct.objects.values('warehouse_id')

它会返回所有对象的 ids(only) 通过过滤器 WarehouseProduct 你得到特定的 id

WarehouseProduct.objects.filter(WarehouseProduct_filed == Value you enter ).first()

【讨论】:

    【解决方案2】:

    由于我的warehouse_id FK是一个模型实例,所以我需要获取这个FK的id,而不是它本身,而当我使用这种方式时,我使用什么魔术方法并不重要:

    Object.warehouse_id.id 效果最好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-07
      • 2012-07-22
      • 2021-01-26
      • 1970-01-01
      相关资源
      最近更新 更多