Django嵌套表单 - 始终显示对象而不是模型详细信息

时间:2018-03-27 17:49:07

标签: django mezzanine

我正在研究通过Mezzanine生成的Django项目。我已经能够创建我的模型,但是我希望有一个表单,管理员可以从列表中选择以分配多对多或一对多关系的值。例如,我有一个Schemas模型:

class Schema(AutoCreatedUpdatedMixin, SoftDeleteMixin):
    """List of all Schemas in a given database"""

    name = models.CharField(max_length=128, null=False)
    status = models.BooleanField(max_length=128, null=False, default=True, verbose_name="Is Active")
    description = models.CharField(max_length=65535, null=True, blank=True, default=None)
    database = models.ForeignKey(Database, on_delete=models.CASCADE)
    pull_requests = models.ManyToManyField(Link)
    questions = models.ManyToManyField(Question, blank=True)
    comments = models.ManyToManyField(Comment, blank=True)
    technical_owners = models.ManyToManyField(Employee, related_name='technical_owners_schemas', blank=True)
    business_owners = models.ManyToManyField(Employee, related_name='business_owners_schemas', blank=True)
    watchers = models.ManyToManyField(Employee, related_name='watchers_schemas', blank=True)

    def __unicode__(self):
        return "{}".format(self.name)

我有一个员工模型

class Employee(AutoCreatedUpdatedMixin, SoftDeleteMixin):
    """List of people with any involvement in tables or fields: business or technical owners, developers, etc"""

    name = models.CharField(max_length=256, blank=False, null=False, default=None, unique=True)
    email = models.EmailField(blank=True, null=True, unique=True)

    def __unicode__(self):
        return "{}".format(self.employee)

员工可以拥有多个架构,架构可以由多个员工拥有。我的数据库中有一个活跃的员工,但是当我尝试创建Schema时,员工显示为Employee Object。相反,我希望表单显示Employee.name。我怎样才能做到这一点?我的管理员文件包含以下内容:

class SchemasAdmin(admin.ModelAdmin):
    list_display = ['name', 'status', 'database', 'description']
    ordering = ['status', 'database', 'name']
    actions = []
    exclude = ('created_at', 'updated_at', 'deleted_at')

enter image description here

1 个答案:

答案 0 :(得分:1)

首先你是使用python 2还是3?对于3,应使用__str__方法而不是__unicode__。我写这篇文章是因为看起来Employee的__unicode__方法存在问题,虽然定义为:

def __unicode__(self):
    return "{}".format(self.employee)

员工类没有employee属性(除非该类继承自(AutoCreatedUpdatedMixin, SoftDeleteMixin)的mixin中有这样的属性,但我不认为是案件。

无论如何,问题是你还没有在__str__上定义一个有效的__unicode__(如果使用python 3)或Employee(用于python 2)方法class - 只需将其定义为:

return self.name

您应该在django管理员选择字段中看到员工的姓名。