python - Filter queryset by reverse exists check in Django -
i have models:
class post(models.model): content = models.charfield() user = models.foreignkey('users.user') active = models.booleanfield(default=true) class comment(models.model): post = models.foreignkey(post, related_name='post_comments')
and queryset filtered query params:
user = request.query_params.get('user_id', none) active = request.query_params.get('active', none) has_comments = request.query_params.get('has_comments', none) qs = post.objects.all() if user: qs = qs.filter(user=user) if active: qs = qs.filter(active=active) if has_comments: ???
i don't how can filter query while maintaining previous filters. possible?
according documentation:
to refer “reverse” relationship, use lowercase name of model.
from this answer follows code be:
if user: qs = qs.filter(user=user) if active: qs = qs.filter(active=active) if has_comments: qs = qs.filter(comment__isnull=false)
with regards performance take this answer account:
django doesn't support select_related() method reverse foreign key lookups, best can without leaving python 2 database queries.
you should have @ prefetch_related
can, unlike select_related
lookups across reverse foreignkeys
, albeit separate query each element of queryset.
Comments
Post a Comment