这个问题是Better Django UI for one to many relationship的扩展。
modles.py
from django.db import models
# Create your models here.
class Dude(models.Model):
name = models.CharField(blank=False, null=False, max_length=100, unique=True)
def phones(self):
# use reverse relation to get a list ofall recorded numbers
phone_numbers = self.phonenumber_set.values_list('number', flat=True)
phone_count = self.phonenumber_set.count()
return "This user have %s numbers recorded: %s" % (phone_count, ', '.join(phone_numbers))
def __unicode__(self):
return u"%s" % self.name
class PhoneType(models.Model):
name = models.CharField(blank=False, null=False, max_length=100, unique=True)
class PhoneNumber(models.Model):
dude = models.ForeignKey(Dude)
number = models.CharField(blank=False, null=False, max_length=100, unique=True)
type = models.ForeignKey(PhoneType)
admin.py
from django.contrib import admin
# Register your models here.
from TestingDjango.apps.one_to_many.models \
import Dude, PhoneNumber
class PhoneNumberInline(admin.TabularInline):
model = PhoneNumber
extra = 1
class DudeAdmin(admin.ModelAdmin):
pass
list_display = ('name', 'phones')
inlines = [ PhoneNumberInline, ]
class PhoneNumberAdmin(admin.ModelAdmin):
pass
list_display = ('dude', 'number')
admin.site.register(Dude, DudeAdmin)
当我添加新的Dude时,我只能选择现有的PhoneType。其他ForeignKey字段没有“+”按钮。我怀疑这是这种一对多关系的二重奏。那么如何为PhoneType添加“+”按钮?
答案 0 :(得分:1)
您需要注册PhoneNumberAdmin才能让Django的管理员访问它,然后它会为您提供' +'添加更多内容的选项。
插入
admin.site.register(PhoneNumber, PhoneNumberAdmin)
位于文件底部