Home > database >  Django type hint for model object (single)
Django type hint for model object (single)

Time:10-27

I'm looking for type hint on an model object instance class:

>>> Device.objects.get(pk=31)
<Device: Device object (31)>
>>> device = Device.objects.get(pk=31)
>>> type(device)
<class 'inventory.models.Device'>

I'll be passing above into a function which will be performing some action but i can't figure out what to use for the device object in the function where type hinting will take place?

def do_something(device: ???) -> bool:
    if device.id:
        some_logic
        return True 

CodePudding user response:

You can reference type as such

from inventory.models import Device

def do_something(device: Device) -> bool:
    # IDE will pick up attributes/methods linked to the model Device
    if device.id:
        some_logic
        return True 

CodePudding user response:

what you want is Dependency inversion, you can pass data as @Mike Jones said

def do_something(device: Device) -> bool:

in general this pattern used with classes, I suggest for you to read more about it to know how you can implement it without any problems

problems I mean if you want to edit your code in future or change somethings on your classes

  • Related