Search code examples
pythonpostgresqlpeewee

Using parameters to return table column values?


I want to be able to use a parameter to determine which columns value to return. But, since 'owner' is a model, the 'assetType' in 'owner.assetType' is treated as an attribute and not as the parameter.

This is just an example of the code I'm working on.

# Owner, by default, owns 1 home, 2 boats, and 3 cars
class Owner(BaseTable):
    homes = IntegerField(null=False, default = 1)
    boats = IntegerField(null=False, default = 2)
    cars = IntegerField(null=False, default = 3)

owner = Owner.get_by_id(1)

allAssets = {
    "House1": {
        "assetType": "homes"
    },
    "Boat1": {
        "assetType": "boats"
    }
}

# returns 'homes'
House1Type = allAssets["House1"].get("assetType")

# returns 1
print(owner.homes)

# AttributeError: 'Owner' object has no attribute 'assetType'
def findValue(assetType):
    print(owner.assetType)

# GOAL: return '1'
findValue(House1Type)

This code does the job and gives me the values I'm looking for, but is turning into a giant if else statement and I'm wondering if there is a more concise way to dynamically get these values.

# if house 1 is type 'boats', show owner.boats value
# if house 1 is type 'homes', show owner.homes value
if House1Type == "boats":
    print("Owned Boats: ",owner.boats)
elif House1Type == "homes":
    print("Owned Homes: ",owner.homes)
else:
    pass

Solution

  • We can optimize the solution by directly calling getattr

    try:
        print(f"Owned {House1Type.title()}: {getattr(owner, House1Type)}")
    except:pass
    

    We can achieve GOAL by using same getattr

    def findValue(assetType):
        return getattr(owner, str(assetType), None)
    
    
    # GOAL: return '1'
    val = findValue(House1Type)
    print(f"Owned {House1Type}: {val}")