django self join query using aliases

2019-09-08 05:37发布

问题:

am trying to use queryset to perform the following query without using raw SQL. 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.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.* ?

回答1:

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.

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.