How to add a calculated field to a Django model

后端 未结 5 1330
情书的邮戳
情书的邮戳 2020-11-28 23:59

I have a simple Employee model that includes firstname, lastname and middlename fields.

On the admin side and li

5条回答
  •  有刺的猬
    2020-11-29 00:10

    Ok... Daniel Roseman's answer seemed like it should have worked. As is always the case, you find what you're looking for after you post the question.

    From the Django 1.5 docs I found this example that worked right out of the box. Thanks to all for your help.

    Here is the code that worked:

    from django.db import models
    from django.contrib import admin
    
    class Employee(models.Model):
        lastname = models.CharField("Last", max_length=64)
        firstname = models.CharField("First", max_length=64)
        middlename = models.CharField("Middle", max_length=64)
        clocknumber = models.CharField(max_length=16)
    
        def _get_full_name(self):
            "Returns the person's full name."
            return '%s, %s %s' % (self.lastname, self.firstname, self.middlename)
        full_name = property(_get_full_name)
    
    
        class Meta:
            ordering = ['lastname','firstname', 'middlename']
    
    class EmployeeAdmin(admin.ModelAdmin):
        list_display = ('clocknumber','full_name')
        fieldsets = [("Name", {"fields":(("lastname", "firstname", "middlename"), "clocknumber")}),
    ]
    
    admin.site.register(Employee, EmployeeAdmin)
    

提交回复
热议问题