屬性內我想知道哪個模型叫它。有沒有辦法做到這一點?如何知道哪個Django模型通過ForeignKey調用屬性?
示例代碼:
# Model One
class ServerOne(models.Model):
user = models.ForeignKey(User)
virtual_machine_server = models.ForeignKey(VirtualMachineServer)
# Model Two
class ServerTwo(models.Model):
virtual_machine_server = models.ForeignKey(VirtualMachineServer)
# Model Three
class VirtualMachineServer(models.Model):
@property
def virtual_machine(self):
# Execute the code based on which model
# is calling this property
return vm
兩個ServerOne和ServerTwo具有VirtualMachineServer作爲一個ForeignKey。我想在此基礎上的模型被稱之爲
實例來調用ServerOne或ServerTwo VirtualMachineServer的虛擬機名財產和執行代碼:
server_one = ServerOne.objects.get(pk=1)
vm = server_one.virtual_machine_server.virtual_machine
server_two = ServerTwo.objects.get(pk=2)
vm = server_two.virtual_machine_server.virtual_machine
我試圖在ServerOne創建一個自定義管理器和ServerTwo:
class ServerOneManager(models.Manager):
def get_query_set(self):
servers = super(ServerOneManager, self).get_query_set()
for server in servers:
server.virtual_machine_server.child_instance = vm
return servers
,然後尋找在虛擬機名財產child_instance屬性:
@property
def virtual_machine(self):
if not hasattr(self, "child_instance"):
raise InstanceIsNotSetException()
但它沒有奏效。
注意:child_instance不在數據庫中,它只是動態創建的屬性。
非常感謝您的幫助。