1👍
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
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:
server_one.virtual_machine_server.virtual_machine(server_one)
Source:stackexchange.com