>>> I need to optimize some code related to django db api. >>> Imagine a model like this: >> >>> class Languages( models.Model ): >>> name = models.CharField( max_length=255 ) >>> ... >> >>> class Object ( models.Model ): >>> name = models.CharField( max_length=255 ) >>> languages = models.ManyToManyField( Languages, radio_admin=True ) >> >>> I need to create a form to search Objects: >>> def my_view(request): >>> ... >>> if request.POST: >>> form = MyForm( request.POST ) >>> if form.is_valid(): >>> data = form.cleaned_data >>> objects = Object.objects.all() >>> if data['name']: >>> objects = objects.filter( name__icontains = >>> data['name'] ) >>> if data['languages']: >>> (1) >>> ... >> >>> I need to search an Object with name ILIKE %name% and with the >>> languages specified in the form. data['languages'] looks like: >>> [ u'1',u'2' ] the IDs of each language. >> >>> I needs some help with the code that should be placed in (1). >>> I thought: >>> ---- >>> for language in languages: >>> objects = Object.filter( languages__id = language) >> >> Have a look at 'in' >> filtering:http://www.djangoproject.com/documentation/db-api/#in >> Maybe that can help you out. The code above is certainly not going to >> work, because you try on the model, not the results returned from the >> managaer. Besides, you'd be filtering in an 'AND' combination, not >> 'OR' > > I can't use IN because it returns an Object that has any of the > languages requested.
Sorry, then I missed what you're trying to achieve; I guessed you wanted to have all languages specified by the form (shouldn't 'IN' return that?), and you can then filter those on the name by appending a .filter() to the returned QuerySet. At least, that's what I thought you wanted and would work. > The SQL clause I need is: > select DISTINCT ... from app_object_languages as m2m INNER JOIN > app_object as ob ON ob.id = m2m.object_id where ( m2m.language_id=1 or > m2m.language_id=2); > > I can't get it! > Thank you for your help. > > > --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---