使用django orm进行连接选择

时间:2015-04-02 02:38:22

标签: join django-orm

create table topic (

  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(128) NOT NULL,
  `description` longtext NOT NULL
) 

create table `subscribe` (

  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userid` varchar(128) NOT NULL,
  `topicid` int(11) NOT NULL,
   Foreign Key (topic_id) REFERENCES topic(id)
)

现在,给定userid =“Amy01”,我想获得“Amy01”订阅的所有主题。 使用SQL时,它是:

select t.id, t.name, t.description
 from topic t join subscribe s on t.id = s.topicid
 where s.userid = "Amy01"

如何使用django orm获得相同的选择?

我已经有了解决方案,但我认为这不是很好:

searched_sub = FilterSubscribe.objects.filter(userid = "Amy01").select_related()
searched = []
for sub in searched_sub:
    searched.append(sub.topicid)

然后,搜索到了Amy01订阅的所有主题。

有没有更好的声明来实现这个目标?

1 个答案:

答案 0 :(得分:0)

我找到了一个解决方案:

my_topic = Topic.objects.filter(Subscribe_set _userid =“Amy01”)。distinct()

“Subscribe_set”用于'回调'订阅表。

更重要的是,当你在models.py中定义Subscribe实体时,如果你这样编码:

topic = models.ForeignKey('Topic',related_name ='_subscribe'),

你也可以实现选择:

my_topic = Topic.objects.filter(_subscribe__userid =“Amy01”)。distinct()

参考:https://docs.djangoproject.com/en/1.6/topics/db/queries/#backwards-related-objects