ManyToManyField widget in a django admin change list?

北慕城南 提交于 2019-12-06 13:26:35
William

This is an old topic, but I'm hoping this might help someone else.

To get the values for a ManyToMany field so you can display their values you can do the follow. I'm using list_display as an example.

class TestAdmin(admin.ModelAdmin):
    def get_some_value(self):
        return ", " . join([x.__str__() for x in self.manytomany_field.all()])

    list_display(get_some_value)
    get_some_value.short_description = 'Title' #sets column header to Title

Silly me. I thought that William's manytomany_field was a built-in ModelAdmin object. So I ran his code as is (after putting in the missing parenthesis after join).

Strange to say, it ran without producing an error message. But (None) appeared when I was supposed to get values. And I thought it was strange that I couldn't find anything when I Googled "django model.Admin.manytomany_field". Hah!

So eventually I realized that I was to put the NAME of the many-to-many field in place of manytomany_field. It works!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!