2

I'm not sure that my title really made sense. Basically (from the code below), when I access the admin screen, I want a project to display with its client and a client to display all attached projects. Is there any way to do this?

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
4

2 回答 2

2

我建议设置一个自定义ModelAdmin并使用 list_display 来指示您要在管理员中显示哪些字段。它是相当可定制的,您可以添加可以准确显示您指示的信息的可调用对象。下面是客户端模型的示例 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')
于 2013-10-05T03:58:20.630 回答
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)
于 2013-10-05T03:48:53.033 回答