2013-10-05 74 views
2

我不确定我的标题真的有意义。基本上(从下面的代码),当我访问管理屏幕时,我想要一个项目显示其客户端和客户端显示所有附加的项目。有没有办法做到这一点?Django 1.5:在两个管理模型中显示foreignkey值

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 

回答

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) 
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') 
相关问题