Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6143675
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T18:33:08+00:00 2026-05-23T18:33:08+00:00

I have this model: class Institution(models.Model): name = models.CharField(max_length=128, db_index=True) aliases = models.ManyToManyField(‘self’, blank=True)

  • 0

I have this model:

class Institution(models.Model):
    name = models.CharField(max_length=128, db_index=True)
    aliases = models.ManyToManyField('self', blank=True)

I would like to make the most efficient query that return all Institution where name contains the search term AND their aliases Institution. I came with the solution below that work but I was wondering if there’s a simpler/more efficient way to achieve this?

base_query = Institution.objects.filter(name__icontains='term')
pk_query = Q(pk__in=base_query)
aliases_query = Q(aliases__in=base_query)
final_query = Institution.objects.filter(pk_query|aliases_query).distinct()

Here is the SQL of this query:

SELECT DISTINCT `app_institution`.`id`, `app_institution`.`name`
FROM `app_institution` LEFT OUTER JOIN `app_institution_aliases`
ON (`app_institution`.`id` = `app_institution_aliases`.`from_institution_id`)
WHERE (`app_institution`.`id`
IN (SELECT U0.`id` FROM `app_institution` U0 WHERE U0.`name` LIKE %term% )
OR `app_institution_aliases`.`to_institution_id`
IN (SELECT U0.`id` FROM `app_institution` U0 WHERE U0.`name` LIKE %term% ))
ORDER BY `app_institution`.`name` ASC LIMIT 21

UPDATE

By looking at the 2 first answers I got, I think I should specify more clearly what I want as results.

I want the UNION of

  • the results of the base_query (Institution where name contains the search term)

WITH

  • aliases of each of the Institution return by the base_query (theses aliases‘ name don’t need to contains the search term).

Done in an inefficient (but easily understandable) way will be like that:

base_query = Institution.objects.filter(name__icontains='term')
results= set(base_query)
for institution in base_query:
    results.update(institution.aliases.all())

2nd UPDATE

Thinking about S.Lott answer, I finally figure out a way to do it with two queries that I join together after.

base_query = Institution.objects.filter(name__icontains='term')
results= set(base_query)
aliases_query = Institution.objects.filter(aliases__in=base_query)
results.update(aliases_query)

I did some small benchmarks and this solution take around half time of the one with the one big query.

But something that I forgot to take into account is the impact on the ordering…

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T18:33:09+00:00Added an answer on May 23, 2026 at 6:33 pm

    Union queries — like this — are difficult.

    It’s important to review the use cases to be sure you really need to conflate two separate collections (by name and by alias) like this. Sometimes the web page can be presented with two collections, removing the need for a union.

    Using Q objects to build “or” conditions is one way to create a union.

    Assembling a separate collection from the two queries is another solution.

    name_query = Institution.objects.filter(name__icontains='term')
    aliases_query = Institution.objects.filter(aliases__name__icontains='term')
    final_query = list(name_query) + list(aliases_query)
    

    The only way to know which is better is to benchmark the alternatives. The “complexity” of the SQL query text doesn’t really mean much, because there are so many optimization steps inside an RDBMS.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this model: class People(models.Model): name = models.CharField(max_length=128, db_index=True) friends = models.ManyToManyField('self') So
I have this model: class Journals(models.Model): jid = models.AutoField(primary_key=True) code = models.CharField(Code, max_length=50) name
If I have this model: class Person(models.Model): name=models.CharField(max_length=28) mother=models.ForeignKey(self,null=True,blank=True) I am trying to make
I have this setup in my models: class Author(models.Model): name = models.CharField(max_length=100) class Topic(models.Model):
So, say I have models like this: class Foo(Model): name = CharField(max_length=200) def latest_comment(self):
..whatdoyoucallitanyway.. I have this model: class Kaart(models.Model): name = models.CharField(max_length=200, name=Kaardi peakiri, help_text=Sisesta kaardi
I have this model: class Category(models.Model): name = models.CharField() description = models.CharField(blank=True) parent =
I have this model: class Address(models.Model): street = models.CharField(blank=True, max_length=300, verbose_name='Straat') house_number = models.CharField(blank=True,
Suppose I have this model: class PhotoAlbum(models.Model): title = models.CharField(max_length=128) author = models.CharField(max_length=128) class
I have this model in django: class JournalsGeneral(models.Model): jid = models.AutoField(primary_key=True) code = models.CharField(Code,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.