django显示多方字段的内容 [英] django display content of a manytomanyfield

查看:121
本文介绍了django显示多方字段的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几天前,我开始使用django框架,非常需要我的应用程序帮助。

I started using django framework just a few days ago and i desperately need some help with my application.

它由客户,项目,管理员和管理员付款组成

It consists of client,project,admin,and admin payment classes where the admin_payment holds the ids of the admins and projects among other stuff.

我的问题是我如何显示我每个项目的管理员名称管理员项目清单?项目类本身不包含管理员ID(Admin_Payment拥有)

My question is how i can display the "administrator's name" of each "project" in my admin listing of projects? the project class itself does not hold the administrator ids (the Admin_Payment does)

当前,我具有以下结构:(分条)

Currently i have the following structure: (striped down)

models.py

models.py

class Admin(models.Model):
    admin_name = models.CharField(unique = True, blank = False, null = False, max_length = 128, verbose_name = u'admin full name')

    def __unicode__(self):
        return self.admin_name
    class Meta:
        ordering = ('id',)
        verbose_name = u'Admin Info'

class Project(models.Model):
    client = models.ForeignKey(Client, verbose_name = u'Client')
    description = models.ForeignKey(Description, verbose_name = u'project description')
    admins = models.ManyToManyField(Admin, verbose_name = u'Administrators', through = 'Admin_Payment')

class Admin_Payment(models.Model):
    admin = models.ForeignKey(Admin, verbose_name = u'Administrator')
    project = models.ForeignKey(Project, verbose_name = u'project')

admin.py(向下扩展)

admin.py (striped down)

class AdminInline(admin.TabularInline):
    model = Admin

class ProjectAdmin(admin.ModelAdmin):
    radio_fields = {'position': admin.HORIZONTAL, 'solution': admin.HORIZONTAL}
    inlines = [AdminInline, ]
    list_display = ['client','description','admin_name']

客户端和说明在项目列表中正确显示,但管理员名称不是

Clients and Descriptions appear correctly in the project listing but the admin names are not

任何帮助都是值得的
(对不起,如果我发布了没有任何意义的内容,我是python和django的新手)

Any help is appreciated (sorry if i posted anything that doesnt make sense , i am a newbie in python and django)

推荐答案

默认情况下,django不支持显示 ManyToMany 字段的内容,因为数据库会查询结果的每一行。您可以通过 Project -model

Displaying the contents of ManyToMany field isn't supported by default by django, because the database will be queried for each row of the results. You can display it yourself by adding a method to your Project-model:

class Project(models.Model):
    ....
    def admin_names(self):
        return ', '.join([a.admin_name for a in self.admins.all()])
    admin_names.short_description = "Admin Names"

并放入 admin_names 在您的 list_display 字段中!

这篇关于django显示多方字段的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆