我想弄清楚如何在Django中使用代理類。我想收到一個查詢集,其中每個對象都屬於公共超類的代理類,以便我可以運行具有相同名稱的自定義子分類方法,而我的控制器邏輯不需要知道或關心哪種代理它正在使用的模型。我不想做的一件事是將信息存儲在多個表中,因爲我想要統一標識符以便於參考/管理。django異構查詢集代理模型
我對django/python很新,所以我很樂意聽到其他方法來完成我想要做的事情。
以下是我有:
TYPES = (
('aol','AOL'),
('yhoo','Yahoo'),
)
class SuperConnect(models.Model):
name = models.CharField(max_length=90)
type = models.CharField(max_length=45, choices = TYPES)
connection_string = models.TextField(null=True)
class ConnectAOL(SuperConnect):
class Meta:
proxy = True
def connect(self):
conn_options = self.deconstruct_constring()
# do special stuff to connect to AOL
def deconstruct_constring(self):
return pickle.loads(self.connection_string)
class ConnectYahoo(SuperConnect):
class Meta:
proxy = True
def connect(self):
conn_options = self.deconstruct_constring()
# do special stuff to connect to Yahoo
def deconstruct_constring(self):
return pickle.loads(self.connection_string)
現在我想做的事情是這樣的:
connections = SuperConnect.objects.all()
for connection in connections:
connection.connect()
connection.dostuff
我環顧四周,發現一些黑客,但他們看起來有問題的,並且可能需要我去到數據庫中的每個項目,以獲取數據我可能已經...
有人請救我:)或者我會去用這個技巧:
class MixedQuerySet(QuerySet):
def __getitem__(self, k):
item = super(MixedQuerySet, self).__getitem__(k)
if item.atype == 'aol':
yield(ConnectAOL.objects.get(id=item.id))
elif item.atype == 'yhoo':
yield(ConnectYahoo.objects.get(id=item.id))
else:
raise NotImplementedError
def __iter__(self):
for item in super(MixedQuerySet, self).__iter__():
if item.atype == 'aol':
yield(ConnectAOL.objects.get(id=item.id))
elif item.atype == 'yhoo':
yield(ConnectYahoo.objects.get(id=item.id))
else:
raise NotImplementedError
class MixManager(models.Manager):
def get_query_set(self):
return MixedQuerySet(self.model)
TYPES = (
('aol','AOL'),
('yhoo','Yahoo'),
)
class SuperConnect(models.Model):
name = models.CharField(max_length=90)
atype = models.CharField(max_length=45, choices = TYPES)
connection_string = models.TextField(null=True)
objects = MixManager()
class ConnectAOL(SuperConnect):
class Meta:
proxy = True
def connect(self):
conn_options = self.deconstruct_constring()
# do special stuff to connect to AOL
def deconstruct_constring(self):
return pickle.loads(self.connection_string)
class ConnectYahoo(SuperConnect):
class Meta:
proxy = True
def connect(self):
conn_options = self.deconstruct_constring()
# do special stuff to connect to Yahoo
def deconstruct_constring(self):
return pickle.loads(self.connection_string)
我實現了一些適用於我的東西,並且可以輕鬆擴展。我有一個要點:https://gist.github.com/3087108 – bencevolta 2012-07-11 01:00:12