python - Django - get results of query based on many to many relationship -


given following models , array of strings via uri get, how can efficiently execute filter operation , return trail matches?

class trail(models.model):     '''     main model application.  contains information particular trail     '''     trail_name = models.charfield(max_length=150)     active = models.booleanfield(default=true)     date_uploaded = models.datetimefield(default=now())     owner = models.foreignkey(account, default=1)  class surface(models.model):     '''     many many join table map surface type many trails.  trail can have many     surface types.     '''     type = models.charfield(max_length=50, db_column='surface_type', unique=true)     trails = models.manytomanyfield(trail)      class meta:         ordering = ('type', ) 

naively, can trail models , iterate through them matches, more efficient way.

i've attempted this:

from django.models.db import q  #list of strings result of url querystring #?keys=dirt&keys=gravel&keys=paved keys = request.get.getlist('keys')  queries = [q(type = surface) surface in keys] query = queries.pop()  item in queries:      query |= item  results = trail.objects.filter(surface=type) 

but returns valueerror: invalid literal int() base 10: exception.

there's no need use q here @ all. presumably have list of strings corresponding type field of surface objects, , want trails related surfaces. can use __in query multiple surface types, , can use double-underscore relationship cross relationship between surface , trail. so:

trail.objects.filter(surface__type__in=request.get.getlist('keys')) 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -