Home > Software design >  Query with multiple foreign keys (django)
Query with multiple foreign keys (django)

Time:04-28

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?

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

CodePudding user response:

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
)
  • Related