Ska*_*Ska 63 django django-models django-queryset
假设我的models.py中有类似的东西:
class Hipster(models.Model):
name = CharField(max_length=50)
class Party(models.Model):
organiser = models.ForeignKey()
participants = models.ManyToManyField(Profile, related_name="participants")
Run Code Online (Sandbox Code Playgroud)
现在在我的views.py中,我想做一个查询,它将为有超过0个参与者的用户取一个派对.
这样的事情可能是:
user = Hipster.get(pk=1)
hip_parties = Party.objects.filter(organiser=user, len(participants) > 0)
Run Code Online (Sandbox Code Playgroud)
这样做的最佳方式是什么?
sol*_*tic 111
如果这样可行,这就是我要做的.
最好的方法可能意味着很多东西:最佳性能,最易维护等.因此我不会说这是最好的方法,但我喜欢尽可能多地坚持ORM功能,因为它似乎更易于维护.
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))
Run Code Online (Sandbox Code Playgroud)
Yuj*_*ita 32
Party.objects.filter(organizer=user, participants__isnull=False)
Party.objects.filter(organizer=user, participants=None)
Run Code Online (Sandbox Code Playgroud)
使用起来更容易exclude:
# organized by user and has more than 0 participants
Party.objects.filter(organizer=user).exclude(participants=None)
Run Code Online (Sandbox Code Playgroud)
还返回不同的结果
派生自 @Yuji-'Tomita'-Tomita 答案,我还添加了 .distinct('id') 以排除重复记录:
Party.objects.filter(organizer=user, participants__isnull=False).distinct('id')
Run Code Online (Sandbox Code Playgroud)
因此,每一方只列出一次。
| 归档时间: |
|
| 查看次数: |
16763 次 |
| 最近记录: |