简体   繁体   English

Django admin外键相关

[英]Django admin foreign key related

I have such models. 我有这样的模型。

class Country(models.Model)
    name = models.CharField(200)

class Zone(models.Model)
    country = models.ForeignKey(Country)
    name = models.CharField(200)

class Town(models.Model)
    zone = models.ForeignKey(Zone)
    name = models.CharField(200)

class Resource(models.Model)
    country = models.ForeignKey(Country)
    zone = models.ForeignKey(Zone)
    town = models.ForeignKey(Town)
    name = models.CharField(max_length=200)
    ...

I want to edit Resource model in django admin. 我想在Django管理中编辑资源模型。 As I have 3 million town records, when I try to edit Resource, site halts because of town. 由于我有300万个城镇记录,因此当我尝试编辑Resource时,站点会因为城镇而暂停。 I just want to select towns related to zones only. 我只想选择仅与区域相关的城镇。 If Zone is changed in Resource admin page, then related towns are displayed also. 如果在“资源管理”页面中更改了区域,那么还将显示相关的城镇。

Is there any idea to implement this? 有什么想法可以实现吗?

I could do it when I display admin form using this function https://docs.djangoproject.com/en/1.4/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey 当我使用此功能显示管理表单时,我可以这样做https://docs.djangoproject.com/en/1.4/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey

but I just want to load towns dynamically according to zone. 但我只想根据区域动态加载城镇。

What you're looking for is the chained select feature of django-smart-selects . 您正在寻找的是django-smart-selects的链接选择功能。

It will populate select box B when a value changes in select box A. 当选择框A中的值更改时,它将填充选择框B。

An alternative option to solution You want, would be to use the built-in raw_id_fields attribute in your ModelAdmin class. 您想要的解决方案的另一种选择是使用ModelAdmin类中的内置raw_id_fields属性。

Foreign keys specified in the raw_id_fields option will display currently selected value (town in your case) and a link that opens a full-featured list of towns with sorting, filtering and search form. raw_id_fields选项中指定的外键将显示当前选择的值(在您的情况下为城镇),以及一个链接,该链接会打开一个功能齐全的城镇列表,其中包括排序,过滤和搜索表单。 Example screenshot from Django docs: Django文档的示例屏幕截图:

See docs for more: https://docs.djangoproject.com/en/1.4/ref/contrib/admin/#django.contrib.admin.ModelAdmin.raw_id_fields 有关更多信息,请参见文档: https : //docs.djangoproject.com/zh-CN/1.4/ref/contrib/admin/#django.contrib.admin.ModelAdmin.raw_id_fields

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM