SQL Alchemy。有许多关系返回特定列

时间:2015-12-22 16:12:25

标签: python sql sqlalchemy

我有以下表格:

Campaigns
+----------------------------+-------------------------------------------------------------------+------+-----+-------------------+----------------+
| Field                      | Type                                                              | Null | Key | Default           | Extra          |
+----------------------------+-------------------------------------------------------------------+------+-----+-------------------+----------------+
| id                         | int(11) unsigned                                                  | NO   | PRI | NULL              | auto_increment |
| campaign_type_id           | int(11)                                                           
+----------------------------+-------------------------------------------------------------------+------+-----+-------------------+----------------+

CampaignsSiteList
+--------------+------------+------+-----+---------+-------+
| Field        | Type       | Null | Key | Default | Extra |
+--------------+------------+------+-----+---------+-------+
| campaign_id  | int(11)    | NO   | PRI | NULL    |       |
| site_list_id | int(11)    | NO   | PRI | NULL    |       |
+--------------+------------+------+-----+---------+-------+

我正在使用SQL Alchemy,我想创建一个关系,以便Campaign类的对象具有一个属性,该属性返回与之关联的site_list_id列表。我不希望关系返回CampaignSiteList对象列表,而是包含CampaignsSiteList列site_list_id的列表。

1 个答案:

答案 0 :(得分:2)

你可以在课堂上使用一个属性并自己将它们拉出来,例如:

class Campaigns():

   # column definitions here

   sites = relationship("CampaignSiteList", lazy="joined")

   @property
   def site_ids(self):
       return [d.id for d in self.sites]