21π
β
I would suggest you to use a custom manager for your class, like this you could use :
nserv = service.objects.are_active()
This would be achieved with something like:
class ServiceManager(models.Manager):
def are_active(self):
# use your method to filter results
return you_custom_queryset
See custom managers
π€Lapin-Blanc
31π
I just had a similar issue. The problem was i had to return a QuerySet instance. A quick solution for me was to do something like this:
active_serv_ids = [service.id for service in Service.objects.all() if service.is_active()]
nserv = Service.objects.filter(id__in=active_serv_ids)
Iβm pretty sure this is not the prettiest and performant way to do this, but it works for me.
A more verbose way of doing this would be:
active_serv_ids = []
for service in Service.objects.all():
if service.is_active():
active_serv_ids.append(service.id)
nserv = Service.objects.filter(id__in=active_serv_ids)
π€user1721105
- [Django]-Can django's auth_user.username be varchar(75)? How could that be done?
- [Django]-Django: Fat models and skinny controllers?
- [Django]-What does this "-" in jinja2 template engine do?
17π
You may not be able to, instead you can post-process the queryset with a list comprehension or generator expression.
For example:
[x for x in Q if x.somecond()]
- [Django]-How can I use Django permissions without defining a content type or model?
- [Django]-Rendering a template variable as HTML
- [Django]-ValueError β Cannot assign: must be an instance
11π
The answer by Ignacio is interesting, but it does not return a queryset. This one does:
def users_by_role(role):
users = User.objects.all()
ids = [user.id for user in users if user.role == role]
return users.filter(id__in=ids)
π€blueFast
- [Django]-Django FileField: How to return filename only (in template)
- [Django]-How do I create sub-applications in Django?
- [Django]-Are sessions needed for python-social-auth
Source:stackexchange.com