[Fixed]-How to know which Django model is calling the property through the ForeignKey?


If only one server points to the virtual machine server, then you can use a reverse lookup, e.g. with a related name. So if ServerOne’s ForeignKey to VirtualMachineServer has the related name server_one and ServerTwo’s ForeignKey has server_two, then you can do something along the lines of

if self.server_one:
    # Do something
elif self.server_two:
    # Do something else
    # No server!

ForeignKeys also automatically have a related name created by appending the suffix _set, e.g. VirtualMachineServer.serverone_set.all().

Alternatively, if there are multiple objects with ForeignKeys to the VirtualMachineServer, then you could just add a parameter to virtual_machine that specifies what object is referring to it. Then you could act accordingly. For example:


Leave a comment