Search code examples
pythondjangodjango-ormm2m

Search M2M fields by names not by id in django


I need have a search box, one of fields of the model has a M2M field. I got to put it works but only works when i look for the id of the M2M field, not for the name. my models:

class Specialities(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name


 class Profile(models.Model):
        user = models.OneToOneField(User)
        name = models.CharField(max_length=200)
        specialities = models.ManyToManyField(Specialities)

        def __str__(self):
            return self.name

And my view:

class SearchView(TemplateView):
    template_name = 'contadores/search.html'

    def post(self,request,*args,**kwargs):
        buscar = request.POST['buscar']
        contadores = Profile.objects.filter(specialities=buscar)
        ctx = {'contadores':contadores}
        return render_to_response('contadores/resultados.html',ctx,context_instance=RequestContext(request))

The queryset in "contadores" works fine, but as i told before, the search box only receive the id of the M2M field, if i look for the word in the search box django says: invalid literal for int() with base 10: 'niif' I know the reason, but how can i pass to the search box the word of the M2M field associated to the Specialities model instead the id?


Solution

  • What you can do is search by related table, like this:

    contadores = Profile.objects.filter(specialities__name__iexact = request.POST['buscar'])