Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Query with multiple foreign keys (django)

I’m making a searchbar for a site I’m working on and I’m having trouble when I want to filter different fields from different models (related between them) Here are my models:

class Project(models.Model):
name = models.CharField(max_length=250)
objective = models.CharField(max_length=250)
description = models.TextField()
launching = models.CharField(max_length=100, null=True, blank=True)
image = models.ImageField(
    upload_to='imgs/', null=True, blank=True)
image_thumbnail = models.ImageField(
    upload_to='thumbnails/', null=True, blank=True)
slug = models.CharField(max_length=250)

class Meta:
    db_table = 'project'

def __str__(self):
    return self.name



class Institution(models.Model):
name = models.CharField(max_length=250)
project = models.ManyToManyField(Proyecto)

class Meta:
    db_table = 'institution'

def __str__(self):
    return self.name

And I want to be able to search by the name of the project or the institution, but my code only takes the institution’s name.

def searchbar(request):
if request.method == 'GET':
    search = request.GET.get('search')
    post = Project.objects.all().filter(name__icontains=search, institution__name__icontains=search)
    return render(request, 'searchbar.html', {'post': post, 'search': search})

How can I search for all the projects that match by its name OR the institution’s name?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

BTW, I’m using SQL, not sure if it’s relevant, but I thought I should add that info.

>Solution :

You can .filter(…) [Django-doc] with Q objects [Django-doc]:

from django.db.models import Q

Project.objects.filter(Q(name__icontains=search) | Q(institution__name__icontains=search))

or you can work with the _connector parameter:

from django.db.models import Q

Project.objects.filter(
    name__icontains=search,
    institution__name__icontains=search,
    _connector=Q.OR
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading