列表显示中的django多对多字段,用于计数之类的项目

django many-to-many-field in list display for item like count

我想在 Django 管理 list_display 中显示每个项目的总点赞数。多对多字段与用户模型相关联。下面是我的代码

型号:

class Item(models.Model):
    title = models.CharField(max_length=100)
    description= RichTextField(blank=True, null=True)
    main_image= models.ImageField(null=False, blank=False,upload_to='images/')
    upload = models.FileField(upload_to ='uploads/')
    date = models.DateTimeField(auto_now_add=True)
    item_category = models.ForeignKey(Categories, default='Coding', on_delete=SET_DEFAULT)
    item_tool = models.ForeignKey(Tools, default='XD', on_delete=SET_DEFAULT)
    slug = models.SlugField(unique=True, blank=True, null=True) # new
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    likes = models.ManyToManyField(User, related_name='post_likes')

    def total_likes(self):
        return self.likes.count()

Admin.py

from django.contrib import admin
from .models import Categories, Item, Tools

class ItemAdmin(admin.ModelAdmin):
    list_display = ('title','author','item_category','date')
    list_filter = ('item_category',)


admin.site.register(Categories)
admin.site.register(Item, ItemAdmin)
admin.site.register(Tools)

您可以将自定义显示添加到您的 list_display 到 return 喜欢的数量,如下所示:

class ItemAdmin(admin.ModelAdmin):
    list_display = ('title','author','item_category','date','likes_count')
    list_filter = ('item_category',)

    def likes_count(self, obj):
        return len(obj.likes.all())
    likes_count.short_description = 'Likes'

    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).prefetch_related('likes')

请注意 get_queryset 的额外更改,以帮助通过使用 prefetch_related 减少数据库命中。没有它,每行 Item 个实例将命中数据库以获取喜欢的数量。

更新:

另一种方法是用喜欢的总数来注释每个项目,如下所示:

class ItemAdmin(admin.ModelAdmin):
    list_display = ('title','author','item_category','date','likes_count')
    list_filter = ('item_category',)

    def likes_count(self, obj):
        return obj.likes_count
    likes_count.short_description = 'Likes'
    likes_count.admin_order_field = 'likes_count'

    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).annotate(likes_count=Count('likes'))

这将支持使用admin_order_field按赞数排序。