与驾驶执照有关的问题。许可证具有指定的人员,该人员具有多种驾驶技能。每类驾驶技能都有一个续订日期和可能的多个相关限制
Name
Lic Cat
Renewal date
Restrictions
Tommy
AM
12/05/15
44.01, 101, 999
Tommy
E+B
14/12/16
Tommy
C
18/04/18
101
TG
E+C
14/12/16
90, 101, 999,
TG
B
18/04/18
105
models.py
class Employee(models.Model):
name = models.CharField(max_length=75)
class DrivingLicenceCategory(models.Model):
name = models.CharField(max_length=11)
class IssuingBody(models.Model):
name = models.CharField(max_length=75)
class DrivingLicence(models.Model):
employee_id = models.ForeignKey(Employee)
driver_number = models.CharField(max_length=49)
permit_number = models.CharField(max_length=49)
issuing_body = models.ForeignKey(IssuingBody)
expiry_date = models.DateField()
class DrivingLicenceRestrictions(models.Model):
name = models.CharField(max_length=21)
description = models.CharField(max_length=1024, blank=True, null=True)
class DrivingLicenceCategoryRestrictions(models.Model):
licence_category = models.ForeignKey(DrivingLicenceCategory)
licence_restriction = models.ForeignKey(DrivingLicenceRestrictions)
expiry_date = models.DateField()
class DrivingLicenceDetail(models.Model):
driving_licence = models.ForeignKey(DrivingLicence)
category_restriction = models.ManyToManyField(DrivingLicenceCategoryRestrictions)
admin.py
from django.contrib import admin
from drvlic.models import *
class DrvLicIssuingBodyAdmin(admin.ModelAdmin):
search_fields = ('^name', )
class DrvLicCategoryAdmin(admin.ModelAdmin):
search_fields = ('^name',)
class DrvLicRestrictionsAdmin(admin.ModelAdmin):
search_fields = ('^name', )
list_display = ('id', 'name', 'description',)
class DrvLicLicenceAdmin(admin.ModelAdmin):
search_fields = ('^employee',)
class DrvLicCategoryRestrictionsAdmin(admin.ModelAdmin):
search_fields = ('^employee',)
filter_horizontal = ('licence_category', 'licence_restriction')
admin.site.register(DrvLicIssuingBody, DrvLicIssuingBodyAdmin)
admin.site.register(DrvLicCategory, DrvLicCategoryAdmin)
admin.site.register(DrvLicRestrictions, DrvLicRestrictionsAdmin)
admin.site.register(DrvLicLicence, DrvLicLicenceAdmin)
admin.site.register(DrvLicCategoryRestrictions, DrvLicCategoryRestrictionsAdmin)
我的模型在Django Admin中生成上面的表是正确的还是模型应该不同?如何设置admin.py以允许访问并输入数据?
Django告诉我'DrvLicCategoryRestrictionsAdmin.filter_horizontal[0]' must be a ManyToManyField'
。如果models.py的构造不正确,我认为这是不可能的。
答案 0 :(得分:0)
搜索字段不需要“^”。只需search_fields = 'name'
即可。
要显示ManyToManyField,您需要遍历所有关联的对象。但是,即使在此之前,我认为你需要重新构建你的模型,以拥有一个“全包围”的模型来保存你想要制作的表格。所以,像:
models.py
class License(models.Model):
employee = models.ForeignKey(Employee)
category = models.ManyToMany(DrivingLicenceCategory)
restriction = models.ManyToMany(DrivingLicenceRestrictions)
expiry_date = models.DateField()
def get_categories(self):
return ",<br>".join([a.name for a in self.category.all()])
def get_restrictions(self):
return ",<br>".join([a.name for a in self.restriction.all()])
admin.py
class LicenseAdmin(admin.ModelAdmin):
list_display = ('employee', 'get_categories', 'get_restrictions', 'expirary_date')