python - 在 django admin 的 list_editable 中实现一对多编辑的直接方法是什么?

标签 python django django-models django-admin

给定以下模型:

class Store(models.Model):
    name = models.CharField(max_length=150)

class ItemGroup(models.Model):
    group = models.CharField(max_length=100)
    code = models.CharField(max_length=20)

class ItemType(models.Model):
    store = models.ForeignKey(Store, on_delete=models.CASCADE, related_name="item_types")
    item_group = models.ForeignKey(ItemGroup)
    type = models.CharField(max_length=100)

在查看单个 Store 时,Inline 可以很好地将多个 item_types 添加到 Store

内容管理团队希望能够批量编辑商店及其类型。有没有一种简单的方法可以在 list_editable 中实现 Store.item_types,它还允许添加新记录,类似于 horizo​​ntal_filter?如果没有,是否有一个简单的指南来说明如何实现自定义 list_editable 模板?我一直在使用谷歌搜索,但一直无法找到任何结果。

此外,如果有更简单或更好的方法来设置这些模型,使之更易于实现,请随时发表评论。

最佳答案

让 ItemType 成为 Store 的 ManyToManyField 怎么样?

对我来说,如果您要更改 Store 中可用的 ItemType,那么您就是在更改 Store 的属性(而不是 ItemType),这似乎是合乎逻辑的。

例如:

from django.db import models

class ItemGroup(models.Model):
    group = models.CharField(max_length=100)
    code = models.CharField(max_length=20)

class ItemType(models.Model):
    item_group = models.ForeignKey(ItemGroup)
    type = models.CharField(max_length=100)

class Store(models.Model):
    name = models.CharField(max_length=150)
    item_type = models.ManyToManyField(ItemType, related_name="store")

# admin
from django.contrib import admin

class StoreAdmin(admin.ModelAdmin):
    list_display=('name', 'item_type',)
    list_editable=('item_type',)

for model in [(Store, StoreAdmin), (ItemGroup,), (ItemType,)]:
    admin.site.register(*model)

这里出现错误:

File "C:\Python27\lib\site-packages\django\contrib\admin\validation.py", line 43, in validate
% (cls.__name__, idx, field))
django.core.exceptions.ImproperlyConfigured: 'StoreAdmin.list_display[1]', 'item_type' is a ManyToManyField which is not supported.

我通过在 django.contrib.admin.validation 中注释掉第 41-43 行解决了这个问题:

#if isinstance(f, models.ManyToManyField):
#    raise ImproperlyConfigured("'%s.list_display[%d]', '%s' is a ManyToManyField which is not supported."
#        % (cls.__name__, idx, field))

可能不是理想的解决方案,但它似乎对我有用。

关于python - 在 django admin 的 list_editable 中实现一对多编辑的直接方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12201697/

相关文章:

python - 如何在 Matplotlib 极坐标图中添加楔形扇区

python - 具有多个图例条目的 Matplotlib 直方图

python - Django 管理员 : TypeError: __str__ returned non-string (type FieldFile)

django - 如何使用 Celery 和 Django 将任务路由到不同的队列

django - 在 Django 中子类化现有模型

python - 将数据插入 Pandas DataFrame 中,无需索引或列开销(因此无需连接或追加)

python - 使用 sklearn 哈希向量化器获取相似度百分比

python - 如何更改 python 模块的名称或别名

django - "Returning to that page might cause any action you took to be repeated"- Django

python - 如何迭代 Django 模板标签中的 ManyToMany 字段?