我使用forigen键从我的父对象引用另一个对象。但是,当我转到django admin创建的下拉列表时,我得到的是对象名而不是字段值。我该如何将字段值添加到表单中?
admin.py
from django.contrib import admin
from .models import Maintenance
from .models import MaintenanceType
from .models import ServiceType
# Register your models here.
class MaintenanceAdmin(admin.ModelAdmin):
list_display = ('Title','Impact','Service','Description','StartTime','EndTime',)
list_editable = ('Title','Impact','Service','Description','StartTime','EndTime',)
admin.site.register(Maintenance, MaintenanceAdmin)
class MaintenanceTypeAdmin(admin.ModelAdmin):
list_display = ('Type',)
list_editable = ('Type',)
admin.site.register(MaintenanceType, MaintenanceTypeAdmin)
class ServiceTypeAdmin(admin.ModelAdmin):
list_display = ('Service','Service',)
list_editable = ('Service','Service',)
admin.site.register(ServiceType, ServiceTypeAdmin)
models.py
from django.db import models
# Create your models here.
class MaintenanceType(models.Model):
Type = models.CharField(max_length=200)
class Meta:
verbose_name = "Planned Maintenance Types"
verbose_name_plural = "Planned Maintenance Types"
class ServiceType(models.Model):
Service = models.CharField(max_length=200)
class Meta:
verbose_name = "Service Types"
verbose_name_plural = "Service Types"
class Maintenance(models.Model):
Title = models.CharField(max_length=200)
Impact = models.ForeignKey(MaintenanceType)
Service = models.ForeignKey(ServiceType)
Description = models.TextField()
StartTime = models.DateTimeField()
EndTime = models.DateTimeField()
class Meta:
verbose_name = "Planned IT Maintenance"
verbose_name_plural = "Planned IT Maintenance"
答案 0 :(得分:4)
在__str__
模型中实施MaintenanceType
,该模型应返回您希望在下拉列表中显示的任何格式的字符串(以及实际上的其他任何位置)。
您似乎只需要return self.Type
。
答案 1 :(得分:0)
您可以通过设置 unicode 方法来重新指定您想要的内容来指定通过访问对象返回的内容。
所以我认为你的MaintenanceType
应该是
class MaintenanceType(models.Model):
Type = models.CharField(max_length=200)
class Meta:
verbose_name = "Planned Maintenance Types"
verbose_name_plural = "Planned Maintenance Types"
def __unicode__(self):
return self.Type