Search code examples
djangopython-class

Get the id of a model object which is FK of another model object django


I have a model named WarehouseProduct, which has a field warehouse_id which is FK of Warehouse model, and i need to get that warehouse_id, so that it would return the id of that FK Warehouse. I tried using:

def __int__(self):
    return self.id

which returns WareHouse object (6), and another way:

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

which returns id, but the type is Warehouse so i can't convert it to int for further usage.


Solution

  • As my warehouse_id FK is a model instance, I need to get this FK's id, not itself, and when I use this way, it doesn't matter what magic method do I use:

    Object.warehouse_id.id works best.