Django管理站点:需要帮助

时间:2015-02-27 10:21:28

标签: python django django-admin

我正在尝试自定义djando admin.py.I想在类Contribution中注册模型ContributionAdmin。在管理界面中,我需要打印字段application_number来自另一个模型Subscriber的数字。与模型有外键关系。如何做到这一点?

admin.py

class ContributionAdmin(admin.ModelAdmin):
    list_display = ('id','nlcc','subscriber','date','receipt_number','amount', 'status')
    list_filter =  ('nlcc',)
    search_fields = ('receipt_number',)
    exclude = ('subscriber',)
admin.site.register(models.Contribution, ContributionAdmin)

models.py:

class Subscriber(models.Model):
   nlcc = models.ForeignKey(NLCC)
   name = models.CharField(max_length=100,blank=True,null=True)
   type = models.CharField(max_length=50, choices=SUBSCRIBER_TYPE)
   application_date =  models.DateField(null=True)
   application_number =  models.IntegerField()
   staff_agent = models.ForeignKey(StaffAgent, null=True, on_delete=models.SET_NULL)

class Contribution(models.Model):
   nlcc = models.ForeignKey(NLCC)
   subscriber = models.ForeignKey(Subscriber)
   staff_agent = models.ForeignKey(StaffAgent, null=True, on_delete=models.SET_NULL)
   date = models.DateField(null=True)
   initial = models.BooleanField(default=False)
   govt =  models.BooleanField(default=False)
   receipt_number = models.BigIntegerField()
   amount = models.DecimalField(max_digits=10, decimal_places=2)
   status = models.CharField(max_length=50, choices=CONTRIBUTION_STATUS)
   status_date = models.DateField(null=True)
   deleted = models.BooleanField(default=False)
   package = models.ForeignKey('CourierPackage', null=True, on_delete=models.SET_NULL, related_name='contribution')

或者有没有办法返回Subscriber名称而不是对象?

1 个答案:

答案 0 :(得分:1)

创建一个方法,该方法将返回所需的字段,并将此方法的名称添加到list_display

class ContributionAdmin(admin.ModelAdmin):

    list_display = ('id','nlcc','subscriber','application_number',
                    'date','receipt_number','amount', 'status')    

    def application_number(self, obj):
        return obj.subscriber.application_number
    application_number.short_description = "Subscriber's Application Number"

更新:如果您想在name字段的选择框中看到application_numbersubscriber,那么最简单的解决方案是定义{ {1}}模型的{1}}方法:

__unicode__

更新2 :如果订阅者数量过长,您可以使用raw_id_fields属性:

Subscriber

更新3 :要将此字段设为只读,请使用readonly_fields

class Subscriber(models.Model):
    ...
    def __unicode__(self):
        return u'%s: %s' % (self.name, self.application_number)