【问题标题】:django one to many issue at the admin panel管理面板上的 django 一对多问题
【发布时间】:2010-11-14 23:26:52
【问题描述】:

您好,我有这两个模型:

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)

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

问候

【问题讨论】:

    标签: python django django-models django-admin


    【解决方案1】:

    我不确定我是否误解了你,但你的模型目前说“一个办公室可以与多个省份相关联,但每个省份可能只有一个办公室”。这与你想要的相矛盾。改为使用 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
    

    【讨论】:

    • 谢谢,现在工作就像一个魅力!我想我在 django 误解了一对多的含义。只是给未来的观众一个简短的说明,我还必须更改 ProvinceCreator 因为 list_display 不允许 ManyToManyFields: class ProvinceCreator(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('name', 'numberPlate' , 'content', 'office') }), ) 干杯!
    • 此外,约定是对 M2M 字段使用复数名称。抱歉,我的示例没有传达这一点(该死的 c&p!)。此外,如果您要显示所有字段,则不需要定义字段集(除非您明确想要重新排序它们,您现在似乎正在这样做)。祝你好运,同胞 djangonaut!
    猜你喜欢
    • 2012-09-29
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 2018-10-22
    • 1970-01-01
    • 2010-11-17
    • 2014-01-23
    相关资源
    最近更新 更多