[英]django self join query using aliases
am trying to use queryset to perform the following query without using raw SQL.我试图在不使用原始 SQL 的情况下使用 queryset 来执行以下查询。 any idea how can do that?
知道怎么做吗?
select * from category_main a, category_list b, category_main c where b.main_id=c.id and a.id=c.parent_id
UPDATED更新
below are my models下面是我的模型
class Main(models.Model):
slug = models.SlugField()
is_active = models.BooleanField(default=True)
site = models.ForeignKey(Site)
parent = models.ForeignKey('self', blank=True, null=True, limit_choices_to={'parent' : None})
class Meta:
unique_together = (("slug", "parent"))
def __unicode__(self):
return self.slug
class List(models.Model):
main = models.ForeignKey(Main)
slug = models.SlugField(unique=True)
is_active = models.BooleanField(default=True)
parent = models.ForeignKey('self', blank=True, null=True)
def __unicode__(self):
return self.slug
UPDATE更新
Hi, I just managed to find a query that does that for me, I used advised below to join main with main's parent and from there I joined list with main list using the below嗨,我刚刚设法找到一个对我有用的查询,我使用下面的建议将 main 与 main 的父级连接起来,然后我使用下面的方法将列表与主列表连接起来
Main.objects.select_related('main', 'parent').filter(list__is_active=True, maini18n__language='en', list__listi18n__language='en').query.__str__()
'SELECT `category_main`.`id`, `category_main`.`slug`, `category_main`.`is_active`, `category_main`.`site_id`, `category_main`.`parent_id`, T5.`id`, T5.`slug`, T5.`is_active`, T5.`site_id`, T5.`parent_id` FROM `category_main` INNER JOIN `category_maini18n` ON (`category_main`.`id` = `category_maini18n`.`main_id`) INNER JOIN `category_list` ON (`category_main`.`id` = `category_list`.`main_id`) INNER JOIN `category_listi18n` ON (`category_list`.`id` = `category_listi18n`.`list_id`) LEFT OUTER JOIN `category_main` T5 ON (`category_main`.`parent_id` = T5.`id`) WHERE (`category_maini18n`.`language` = en AND `category_list`.`is_active` = True AND `category_listi18n`.`language` = en )'
the returned query mapped everything I need, accept its not being added to the select statement, is there a way so i can force it to select columns from category_list.*?返回的查询映射了我需要的所有内容,接受它没有被添加到 select 语句中,有没有办法让我可以强制它到 category_list 中的 select 列。*?
This does basically what you want:这基本上可以满足您的要求:
lists = List.objects.select_related('main', 'parent')
Note you have to explicitly state the relationships to follow in select_related here, because your parent
relationship has null=True
which isn't followed by default.请注意,您必须在此处明确 state 遵循 select_related 的关系,因为您的
parent
关系具有null=True
,默认情况下不遵循。
This will give you a set of List
objects, but pre-fetch the related Main
and List
objects which you can reference as normal without hitting the db again.这将为您提供一组
List
对象,但预先获取相关的Main
和List
对象,您可以正常引用它们而无需再次访问 db。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.