如何在 Django 中统计 ManyToMany 字段中的艺术家

How to count Artist in ManyToMany Field in Django

我想统计单个艺术家制作的视频数量,请告诉我哪里错了?

这是我在 admin.py 文件中的代码

class ArtistAdmin(admin.ModelAdmin):
    list_display = ['name', 'date_of_birth', 'artist_videos']
    def artist_videos(self, obj):
        count = 0
        for artistcount in Artist.objects.all():
            if artistcount.name == VideoList.artists:
                count = count + 1
        return count

她是我在 models.py

中的代码
class Artist(models.Model):
    name = models.CharField(max_length=200)
    date_of_birth = models.DateTimeField()

    def __str__(self):
        return self.name
class VideoList(models.Model):
    title = models.CharField(max_length=200)
    artists = models.ManyToManyField(Artist)

def __str__(self):
    return self.title

你可以这样进行反向查询:

class ArtistAdmin(admin.ModelAdmin):
    # rest of the code
    def artist_videos(self, obj):
        return obj.videolist_set.all().count()

更多信息请查看documentation

我认为你的问题很简单,就是你检查错了。在声明中:

    ...
    count = 0
    for artistcount in Artist.objects.all():
        if artistcount.name == VideoList.artists:
            count = count + 1

您正在将 string 与 django queryset 进行比较。这将永远是 False.

您实际上在 obj 中收集了 Artist 对象,因此您可以使用:

class ArtistAdmin(admin.ModelAdmin):
    list_display = ['name', 'date_of_birth', 'artist_videos']
    def artist_videos(self, obj): # <-- mind the obj parameter!
        return VideoList.objects.filter(artists__name=obj.name).count()

这样您就可以使用实际的艺术家对象过滤视频。

不过请注意,我还没有检查过我的实际项目,所以我可能是错的:/

祝你好运!

[编辑] 用户@ruddra post 给出了更好的答案。也请参考他的post!总而言之,最好的方法是使用 M2M 关系管理器:

    # previous code
    def artist_videos(self, obj):
        return obj.videolist_set.all().count()

请确保您已迁移您的艺术家模型。 通过 运行 以下命令检查。

python manage.py makemigrations 'Your app name here'

python manage.py migrate 

这次尝试后 在您的 admin.py

中导入以下模型
import Artist
import VideoList

    def artist_videos(self, obj):
        count = Artist.objects.filter(name=VideoList.artists.name).count()
        return count

这样做并告诉我。