Mo J. Mughrabi
Mo J. Mughrabi

Reputation: 6997

django reverse query

Am trying to query from parent to child and with a single query being able to have the child results in parent. In my example, am trying to do a relation between i18n tables in which I want to include the row from the child table in a single hit.

models.py

class main(models.Model):
    slug       = models.SlugField()
    is_active  = models.BooleanField(default=True)
    site       = models.ForeignKey(Site)

    def __unicode__(self):
        return self.slug

class main_i18n(models.Model):
    main        = models.ForeignKey(main)
    language    = models.CharField(max_length=2, choices=LANGUAGES)
    title       = models.CharField(max_length=50)
    class Meta:
        unique_together = (("language", "main"))
    def __unicode__(self):
        return self.title

I tried the following to query

a=main.objects.filter(is_active=True, main_i18n__language='en')

and the relation its done perfectly, here is what I saw when tried to print the query

>>> a.query.__str__()
'SELECT `category_main`.`id`, `category_main`.`slug`, `category_main`.`is_active`, `category_main`.`site_id` FROM `category_main` INNER JOIN `category_main_i18n` ON (`category_main`.`id` = `category_main_i18n`.`main_id`) WHERE (`category_main_i18n`.`language` = en  AND `category_main`.`is_active` = True )'

As you see from the query, it does the join correctly but the column names is not included in the select statement. I cannot access the main_i18n data when trying to do a for loop.

sorry for my lousy english and hope i can find help,

Best wishes,

---- EDIT:

below is the template am currently using, ultimately I would really like to create a single query and do regrouping based to list the data in my view.

    <table class="homepage-listing">
        <tr>
            <td>
{#                {% regroup list by main as rg_main %}#}
                {% for obj in main %}
{#                    {% if obj.grouper != None %}#}
                    <div class="listing-block">
                            <a href="#" ><h3>{{ obj }}</h3></a>
                            <ul>
                                {% for s in obj.list %}
                                    <li>{{ s.list_i18n_set.get }} </li>
                                {% endfor %}
                            </ul>
                    </div>
{#                    {% endif %}#}
                {% endfor %}
            </td>
        </tr>
    </table>

--- EDIT:

I had to use the extra functions to to build a single query for that purpose. I started with it but getting a bit complicated, am trying to make sure the columns not hardcoded in the queries and the joins are correct. Can anyone tell me if there is a better way to write the query?

    dict = Main.objects.extra(
    select=
    {
        'main_title' : '%s.%s' % (MainI18n._meta.db_table, MainI18n._meta.get_field('title').verbose_name),
        'list_title' : '%s.%s' % (ListI18n._meta.db_table, ListI18n._meta.get_field('title').verbose_name),
    },
    tables=[
            '%s' % (MainI18n._meta.db_table),
            '%s' % (List._meta.db_table),
            '%s' % (ListI18n._meta.db_table),
    ],
    where=[
            '%s.%s=%s.%s' % (MainI18n._meta.db_table, 'main_id', Main._meta.db_table, 'id'),
            '%s.main_id=%s.id' % (List._meta.db_table, Main._meta.db_table),
            '%s.list_id=%s.id' % (ListI18n._meta.db_table, List._meta.db_table),
            'category_listi18n.language="%s"' % (request.LANGUAGE_CODE)
    ]).select_related().filter(maini18n__language=request.LANGUAGE_CODE )

Upvotes: 2

Views: 1959

Answers (2)

emulbreh
emulbreh

Reputation: 3461

You could query MainI18N instead:

MainI18N.objects.filter(main__is_active=True, language='en').select_related('main')

EDIT: You can wrap this in a custom queryset method. The quick solution (which doesn't allow you to further filter the QuerySet) would look something like this:

class MainQuerySet(QuerySet):
    def translate(self, lang):
       for obj in MainI18N.filter(language=lang, main__in=self).select_related('main'):
           main = obj.main
           main.i18n = obj
           yield main

Upvotes: 1

Chris Pickett
Chris Pickett

Reputation: 2822

When you use a foreign key you need to access that data through the RelatedManager. In your case you would access data in the main_i18n from the main like:

>>> a=main.objects.get(id=1)
>>> i18n = a.main_i18n_set.get()
>>> i18n.language
u'en'

or if you need to operate on multiple objects:

a = main.objects.filter(is_active=True, main_i18n__language='en')
for obj in a:
  i18n = obj.main_i18n_set.get()
  print i18n.language

which would of course print 'en' for each object return by the filter.

Upvotes: 2

Related Questions