如何在 Django 中为外键做注解?
How to make annotation for foreign key in Django?
我需要用注释替换 _points
属性 以便我有机会按此值对 Django 管理面板中的条目进行排序。
我的模特:
class CustomUser(models.Model):
inviter = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True)
@property
def _points(self):
res = CustomUser.objects.filter(inviter_id=self.id).count()
return res
我的管理员:
class CustomUserAdmin(admin.ModelAdmin):
list_display = ['created', 'updated']
def get_queryset(self, request):
qs = super(CustomUserAdmin, self).get_queryset(request)
qs = qs.annotate(points=(HOW TO CALCULATE _points HERE?).order_by('points')
return qs
inviter
关系的相反方式是 customuser
,因此您可以将其实现为:
from django.db.models import Count
class CustomUserAdmin(admin.ModelAdmin):
list_display = ['created', 'updated']
def get_queryset(self, request):
return super().get_queryset(request).annotate(
<strong>points=Count('customuser')</strong>
).order_by('-points')
不过,将 inviter
的 related_name=…
[Django-doc] 重命名为 invitees
可能更有意义:
class CustomUser(models.Model):
inviter = models.ForeignKey(
'self',
<strong>related_name='invitees'</strong>,
on_delete=models.SET_NULL,
null=True,
blank=True
)
@property
def _points(self):
return self<b>.invitees</b>.count()
那么我们算作:
class CustomUserAdmin(admin.ModelAdmin):
list_display = ['created', 'updated']
def get_queryset(self, request):
return super().get_queryset(request).annotate(
<strong>points=Count('invitees')</strong>
).order_by('-points')
我需要用注释替换 _points
属性 以便我有机会按此值对 Django 管理面板中的条目进行排序。
我的模特:
class CustomUser(models.Model):
inviter = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True)
@property
def _points(self):
res = CustomUser.objects.filter(inviter_id=self.id).count()
return res
我的管理员:
class CustomUserAdmin(admin.ModelAdmin):
list_display = ['created', 'updated']
def get_queryset(self, request):
qs = super(CustomUserAdmin, self).get_queryset(request)
qs = qs.annotate(points=(HOW TO CALCULATE _points HERE?).order_by('points')
return qs
inviter
关系的相反方式是 customuser
,因此您可以将其实现为:
from django.db.models import Count
class CustomUserAdmin(admin.ModelAdmin):
list_display = ['created', 'updated']
def get_queryset(self, request):
return super().get_queryset(request).annotate(
<strong>points=Count('customuser')</strong>
).order_by('-points')
不过,将 inviter
的 related_name=…
[Django-doc] 重命名为 invitees
可能更有意义:
class CustomUser(models.Model):
inviter = models.ForeignKey(
'self',
<strong>related_name='invitees'</strong>,
on_delete=models.SET_NULL,
null=True,
blank=True
)
@property
def _points(self):
return self<b>.invitees</b>.count()
那么我们算作:
class CustomUserAdmin(admin.ModelAdmin):
list_display = ['created', 'updated']
def get_queryset(self, request):
return super().get_queryset(request).annotate(
<strong>points=Count('invitees')</strong>
).order_by('-points')