152π
If this works this is how I would do it.
Best way can mean a lot of things: best performance, most maintainable, etc. Therefore I will not say this is the best way, but I like to stick to the ORM features as much as possible since it seems more maintainable.
from django.db.models import Count
user = Hipster.objects.get(pk=1)
hip_parties = (Party.objects.annotate(num_participants=Count('participants'))
.filter(organiser=user, num_participants__gt=0))
37π
Party.objects.filter(organizer=user, participants__isnull=False)
Party.objects.filter(organizer=user, participants=None)
- [Django]-Uninstall Django completely
- [Django]-Django β Rotating File Handler stuck when file is equal to maxBytes
- [Django]-Django model one foreign key to many tables
6π
Easier with exclude
:
# organized by user and has more than 0 participants
Party.objects.filter(organizer=user).exclude(participants=None)
Also returns distinct results
- [Django]-How to add custom search box in Django-admin?
- [Django]-Redirect to named url pattern directly from urls.py in django?
- [Django]-What is the difference between null=True and blank=True in Django?
5π
Derived from @Yuji-βTomitaβ-Tomita answer, Iβve also added .distinct(βidβ) to exclude the duplitate records:
Party.objects.filter(organizer=user, participants__isnull=False).distinct('id')
Therefore, each party is listed only once.
- [Django]-What's the best way to extend the User model in Django?
- [Django]-How exactly do Django content types work?
- [Django]-Django.contrib.gis.db.backends.postgis vs django.db.backends.postgresql_psycopg2
0π
I use the following method when trying to return a queryset having at least one object in a manytomany field:
First, return all the possible manytomany objects:
profiles = Profile.objects.all()
Next, filter the model by returning only the queryset containing at least one of the profiles:
hid_parties = Party.objects.filter(profiles__in=profiles)
To do the above in a single line:
hid_parties = Party.objects.filter(profiles__in=Profile.objects.all())
You can further refine individual querysets the normal way for more specific filtering.
NOTE:This may not be the most effective way, but at least it works for me.
- [Django]-How to set-up a Django project with django-storages and Amazon S3, but with different folders for static files and media files?
- [Django]-How can I get all the request headers in Django?
- [Django]-How to add custom field in ModelSerializer?