django管理员面板中的一对多问题

时间:2009-07-29 07:35:41

标签: python django django-models django-admin

问候,我有这两个模型:

from django.db import models

class Office(models.Model):
    name = models.CharField(max_length=30)
    person = models.CharField(max_length=30)
    phone = models.CharField(max_length=20)
    fax = models.CharField(max_length=20)
    address = models.CharField(max_length=100)
    def __unicode__(self):
            return self.name



class Province(models.Model):
    numberPlate = models.IntegerField(primary_key=True)
        name = models.CharField(max_length=20)
    content = models.TextField()
    office = models.ForeignKey(Office)
    def __unicode__(self):
            return self.name

我希望能够为省份选择几个办事处,这是一对多的模型。这是我的admin.py:

from harita.haritaapp.models import Province, Office
from django.contrib import admin


class ProvinceCreator(admin.ModelAdmin):
        list_display = ['name', 'numberPlate','content','office']

class OfficeCreator(admin.ModelAdmin):
        list_display = ['name','person','phone','fax','address']


admin.site.register(Province, ProvinceCreator)
admin.site.register(Office, OfficeCreator)

现在,我可以在管理面板上为每个省选择一个Office,同时创建一个新的省但我希望能够选择多个。我怎样才能做到这一点?

此致

1 个答案:

答案 0 :(得分:2)

我不确定我是否误解了你,但你的模特目前说“办公室可以与许多省份联系,但每个省可能只有一个办公室”。这与你想要的相矛盾。请改用ManyToMany字段:

class Province(models.Model):
    numberPlate = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=20)
    content = models.TextField()
    office = models.ManyToManyField(Office)
    def __unicode__(self):
        return self.name