Django 1.5:在两个管理模型中显示foreignkey值

时间:2013-10-05 03:45:20

标签: python django python-2.7 django-models django-admin

我不确定我的头衔是否真的有道理。基本上(从下面的代码),当我访问管理界面时,我想要一个项目与其客户端和客户端一起显示所有附加的项目。有没有办法做到这一点?

class Client(models.Model):
    title = models.CharField(max_length=250, null=True)

    #project = models.ManyToManyField(Project)
    #status = models.CharField(max_length=250)

class Project(models.Model):
    project_choices = (
        ('L1', 'Lead'),
        ('C1', 'Confirmed'),
        ('P1', 'In Progress'),
        ('P1', 'Paid'),

    )
    title = models.CharField(verbose_name='Project Title', max_length=250, null=True)
    client = models.ForeignKey(Client)
    project_status = models.CharField(max_length=2,
                                      choices=project_choices,
                                      default='P1')
    def __unicode__(self):
        return self.title

2 个答案:

答案 0 :(得分:2)

我建议设置自定义ModelAdmin并使用list_display指示要在管理员中显示哪些字段。它是相当可定制的,您可以添加可以显示您指明的信息的callables。客户端模型的示例ModelAdmin如下所示。

# project/app/admin.py
# Callable to add to ModelAdmin List Display
def show_client_projects(obj):
    project_list = [p.title for p in obj.project_set.all()]
    return ', '.join(project_list)
show_client_projects.short_description = 'Client Projects'

# Custom ModelAdmin
class ClientAdmin(admin.ModelAdmin):
    list_display = ('title', 'show_client_projects')

答案 1 :(得分:0)

您需要为模型创建ModelAdmin类,以定义要在内置Django管理员中显示的列:

https://docs.djangoproject.com/en/dev/ref/contrib/admin/

这一点特别相关:

ManyToManyField fields aren’t supported, because that would entail executing a separate SQL statement for each row in the table. If you want to do this nonetheless, give your model a custom method, and add that method’s name to list_display. (See below for more on custom methods in list_display.)

因此,您可以为客户创建一个加载客户项目的方法,并将其包含在list_display中。

这样的事情会让你走上正轨:

# In your models.py...
from django.contrib import admin

class Client(models.Model):
    title = models.CharField(max_length=250, null=True)

    def projects(self):
        return Project.objects.filter(client=self)


class ClientAdmin(models.ModelAdmin):
    list_display = ('title','projects',)
admin.site.register(Client,ClientAdmin)